1

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?

1

2 Answers 2

14

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Should I upvote your answers anymore? You probably don't even notice the +10 with your 86k of reputation. ;)
@SarahVessels: your comment is so funny today.
3

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...

1 Comment

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...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.