Loving Extensions

I saw a post recently where Christopher Bennage talks about his little friend, Enum<T>.   Christopher said that the code was so simple he was almost ashamed of it.  No need to be ashamed dude, the simplest code is the best code! ;)

I thing this is actually an area where Extentions can be used very effectively.

   1: public static TEnum ConvertTo<TEnum>(this string source)


   2: {


   3:     // Validate type of TEnum


   4:     Type typeOfEnum = typeof(TEnum);


   5:     if (typeOfEnum.BaseType != typeof(Enum))


   6:     {


   7:         throw new NotSupportedException("TEnum must be an Enum");


   8:     }


   9:  


  10:     // source cannot be null or empty


  11:     source.ArgumentNotNullOrEmpty("source");


  12:  


  13:     // Parse the string


  14:     return (TEnum)Enum.Parse(typeOfEnum, source);


  15: }




I used ConvertTo as I feel this better describes what we are doing.  And it is easy to use:





   1: SomeEnum se = someEnumString.ConvertTo<SomeEnum>();






Love it.  What is the source.ArgumentNotNullOrEmpty(“source”) in ConvertTo I hear you ask?  Well here is the code for that bit:





   1: /// <summary>


   2: /// Checks a string argument to ensure it isn't null or empty


   3: /// </summary>


   4: /// <param name="argumentValue">The argument value to check.</param>


   5: /// <param name="argumentName">The name of the argument.</param>


   6: public static void ArgumentNotNullOrEmpty(this string argumentValue, string argumentName)


   7: {


   8:     argumentValue.ArgumentNotNull(argumentName);


   9:  


  10:     if (argumentValue.Length == 0)


  11:         throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "{0} cannot be empty", argumentName));


  12: }


  13:  


  14: /// <summary>


  15: /// Checks an argument to ensure it isn't null


  16: /// </summary>


  17: /// <param name="argumentValue">The argument value to check.</param>


  18: /// <param name="argumentName">The name of the argument.</param>


  19: public static void ArgumentNotNull(this object argumentValue, string argumentName)


  20: {


  21:     if (argumentValue == null)


  22:         throw new ArgumentNullException(argumentName);


  23: }




This can be used to check if method parameter values are null or if they are strings, null or empty.  Another cool extention.



If you want more, go and check out the Umbrella project on CodePlex.

Post a Comment

Popular Posts