tags:

views:

283

answers:

3

I'm trying to writing a method that parses a string parameter into an enum. The enum's type is also determined by a parameter. This is what I've started with:

public static type GetValueOrEmpty(string text, Type type)
{
    if (!String.IsNullOrEmpty(text))
    {
     return (type)Enum.Parse(typeof(type)value);
    }
    else
    {
     // Do something else
    }
}

Obviously this won't work for a number of reasons. Is there a way this can be done?

+14  A: 

You can make it generic instead, if you know the type at compile-time:

public static T GetValueOrEmpty<T>(string text)
{
    if (!String.IsNullOrEmpty(text))
    {
        return (T) Enum.Parse(typeof(T), text);
    }
    else
    {
        // Do something else
    }
}

If you don't know the type at compile-time, then having the method return that type won't be much use to you. You can make it return object of course:

public static object GetValueOrEmpty(string text, Type type)
{
    if (!String.IsNullOrEmpty(text))
    {
        return Enum.Parse(type, text);
    }
    else
    {
        // Do something else
    }
}

If neither of these are useful to you, please give more information about what you're trying to achieve.

Jon Skeet
Should I upvote your answers anymore? You probably don't even notice the +10 with your 86k of reputation. ;)
Sarah Vessels
+3  A: 

You need to use a generic method. Something like this should do the trick:

public static TEnum ParseEnum<TEnum>(string s)
{
    return (TEnum)Enum.Parse(typeof(TEnum), s);
}

EDIT: Fixed typo in code...

Arjan Einbu
parts[0] ?
Svish
Ooops... Thanks... Fixed... Typical copy/paste error
Arjan Einbu
I like to add a 'where TEnum : struct' type constraint on these sorts of methods, to try and limit the types it can be called on (C# doesn't allow an 'enum' constraint, 'struct' is the next best thing...)
thecoop
+1  A: 

I really recommend you take a look at the blog post written by my friend: Enumerations and Strings - Stop the Madness! He goes a step further allowing you to easily parse nullable enums also.

Chris Marisic
Interesting !
Alex Angas
I agree, it makes it very easy to work with Enums and IMO all usages of Enums in classes should be made nullable instead of having to deal with parsing default cases to figure out if a user picked something etc.
Chris Marisic