Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Enums and string values: Improved version

Last week I wrote an entry about converting strings into enums by using their associated Stringvalueattribute. Well, my friend Vicente Peña suggested another approach of the GetEnumStringValue method, which will save us the need to make the explicit cast. Here's the code:

1: /// <summary>
2: /// Get an enum from a string value attribute
3: /// </summary>
4: /// <see cref="http://hugonne.blogspot.com/2010/01/enums-and-string-values.html"/>
5: /// <remarks>Created by Vicente Peña</remarks>
6: public static T GetEnumStringValue<T>(this string value, bool ignoreCase)
7: {
8:     object result = null;
9:     Type type = typeof(T);
10:     string enumStringValue = null;
11:     if(!type.IsEnum)
12:         throw new ArgumentException("enumType should be a valid enum");
13: 
14:     foreach(FieldInfo fieldInfo in type.GetFields())
15:     {
16:         var attribs =
17:             fieldInfo.GetCustomAttributes(typeof(StringValueAttribute), false) 
18:             as StringValueAttribute[];
19:         //Get the StringValueAttribute for each enum member
20:         if(attribs != null)
21:             if(attribs.Length > 0)
22:                 enumStringValue = attribs[0].StringValue;
23: 
24:         if(string.Compare(enumStringValue, value, ignoreCase) == 0)
25:             result = Enum.Parse(type, fieldInfo.Name);
26:     }
27: 
28:     if(result != null)
29:     {
30:         return (T) result;
31:     }
32:     throw new ArgumentException("String not found");
33: }

To call it, we just have to do this:

1: UserState enu = "A".GetEnumStringValue<UserState>(true);


This post first appeared on Hugonne - Another .net Coding, please read the originial post: here

Share the post

Enums and string values: Improved version

×

Subscribe to Hugonne - Another .net Coding

Get updates delivered right to your inbox!

Thank you for your subscription

×