An attempt at Enum.TryParse

It is well known fact that Enum.TryParse does not exist in .net 3.5 although it is available in 4.0

There have been some previous implementations already made here, here and here. I thought I should add my $0.02 into the mix & put out my own implementation, so here goes:

Note: line breaks added for clarity & to fit the layout

public static class Extensions{
    public static bool TryParse<T>(this T enum_class,
         string value, out T result){
         return Extensions.TryParse(enumClass, value, true, 
                 out result);
    }
    public static bool TryParse<T>(this T enum_class,
        string value,
        bool ignoreCase, out T result)
        where T : struct
        // cannot constraint by System.Enum type
    {
        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) => e.GetType().IsEnum,
            (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)
        };

        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 can convert the following:

Enum Converted from

enum SomeEnum { A, B, C }

“A” or “a”

enum SomeEnum : int 
{ A = 1, B = 2, C = 3 }

“A” or “a” or 1

[Flags]
enum SomeEnum {
  A = 1, B = 2, C = 4
}

“A” or “a” or “A, B” or “A, b” or “a, B” or “a, b”, 1

Drop a note if you find this useful.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s