Enum.TryParse with Flags attribute

I wrote code for the TryParse enumeration, either by value or by its name, as shown below. How can I extend this code to include parsing enumerations with the Flags attribute?

  public static bool TryParse<T>(this T enum_type, object value, out T result) where T : struct { return enum_type.TryParse<T>(value, true, out result); } public static bool TryParse<T>(this T enum_type, object value, bool ignoreCase, out T result) where T : struct { result = default(T); var is_converted = false; var is_valid_value_for_conversion = new Func<T, object, bool, bool>[]{ (e, v, i) => e.GetType().IsEnum, (e, v, i) => v != null, (e, v, i) => Enum.GetNames(e.GetType()).Any(n => String.Compare(n, v.ToString(), i) == 0) || Enum.IsDefined(e.GetType(), v) }; if(is_valid_value_for_conversion.All(rule => rule(enum_type, value, ignoreCase))){ result = (T)Enum.Parse(typeof(T), value.ToString(), ignoreCase); is_converted = true; } return is_converted; } 

This code currently works for the following enumerations:

 enum SomeEnum{ A, B, C } // can parse either by 'A' or 'a' enum SomeEnum1 : int { A = 1, B = 2, C = 3 } // can parse either by 'A' or 'a' or 1 or "1" 

Doesn't work for:

 [Flags] enum SomeEnum2 { A = 1, B = 2, C = 4 } // can parse either by 'A' or 'a' // cannot parse for A|B 

Thank!

+11
c # coding-style tryparse
Apr 30 '10 at 14:46
source share
3 answers

The @Pop answer gave me the key, and I changed the rule check in my code to look like this:

 var is_valid_value_for_conversion = new Func<T, object, bool, bool>[] { (e, v, i) => e.GetType().IsEnum, (e, v, i) => value != null, (e, v, i) => Enum.GetNames(e.GetType()).Any( n => String.Compare(n, v.ToString(), i) == 0 || (v.ToString().Contains(",") && v.ToString().ToLower().Contains(n.ToLower()))) || Enum.IsDefined(e.GetType(), v) }; 

the rest remains the same and it works for me

Hth someone else

0
Apr 30 '10 at 15:31
source share

Flag enumerations are written using , using the .Net convention, not | . Enum.Parse () works great when using the strings ",":

 [Flags] public enum Flags { A = 1, B = 2, C = 4, D = 8, } var enumString = (Flags.A | Flags.B | Flags.C).ToString(); Console.WriteLine(enumString); // Outputs: A, B, C Flags f = (Flags)Enum.Parse(typeof(Flags), enumString); Console.WriteLine(f); // Outputs: A, B, C 
+26
Apr 30 '10 at 14:57
source share

Starting with .NET 4, there is an Enum.TryParse <T> method. It supports flag enumerations out of the box:

 string x = (SomeEnum2.A | SomeEnum2.B).ToString(); // x == "A, B" SomeEnum2 y; bool success = Enum.TryParse<SomeEnum2>(x, out y); // y == A|B 
+15
Apr 30 '10 at 14:57
source share



All Articles