2

Possible Duplicate:
How do I Convert a string to an enum in C#?

I have an enum of type int:

public enum BlahType
{
       blah1 = 1,
       blah2 = 2
}

If I have a string:

string something = "blah1"

How can I convert this to BlahType?

Community
  • 1
  • 1
mrblah
  • 99,669
  • 140
  • 310
  • 420

4 Answers4

8

I use a function like this one

public static T GetEnumValue<T>(string value)
{
    return (T)Enum.Parse(typeof(T), value);
}

And you can call it like this

BlahType value = GetEnumValue<BlahType>("Blah1");
Pierre-Alain Vigeant
  • 22,635
  • 8
  • 65
  • 101
7

You want Enum.Parse

BlahType blahValue = (BlahType) Enum.Parse(typeof(BlahType), something); 
Winston Smith
  • 21,585
  • 10
  • 60
  • 75
2

I use this function to convert a string to a enum; then you can cast to int or whatever.

public static T ToEnum<T>(string value, bool ignoreUpperCase)
        where T : struct, IComparable, IConvertible, IFormattable {
        Type enumType = typeof (T);
        if (!enumType.IsEnum) {
            throw new InvalidOperationException();
        }
        return (T) Enum.Parse(enumType, value, ignoreUpperCase);
}
Jhonny D. Cano -Leftware-
  • 17,663
  • 14
  • 81
  • 103
  • Nice extension method. I just wonder why should it ignore uppercase only rather than just ignore case? ;) – Fredrik Mörk Nov 05 '09 at 21:14
  • 1
    When I first did that function, I though about checking for if the given type was an enum. I gave up after discovering (with reflector) that Enum.Parse already do these check (and more) and throw a ArgumentException if the type is not an enum. – Pierre-Alain Vigeant Nov 05 '09 at 21:15
  • sorry, that's a spanish translation issue, it's just a wrapper for the overload of Enum.Parse – Jhonny D. Cano -Leftware- Nov 06 '09 at 12:51
1
    public enum BlahType
    {
        blah1 = 1,
        blah2 = 2
    }

    string something = "blah1";
    BlahType blah = (BlahType)Enum.Parse(typeof(BlahType), something);

If you are not certain that the conversion will succeed - then use TryParse instead.

Philip Wallace
  • 7,905
  • 3
  • 28
  • 40