tags:

views:

291

answers:

6

I have an enum like:

public enum BlahType
{
    blahA = 1,
    blahB = 2,
    blahC = 3
}

if I have a string with the value 'blahB', is it possible to cast it against the enum BlahType to get the value 2?

+1  A: 

You can use the Enum.Parse method and then cast to int.

Jakob Christensen
+5  A: 

Use:

BlahType yourEnumValue = (BlahType) Enum.Parse(typeof(BlahType), "blahB");

and then

int yourIntValue = (int) yourEnumValue;
Jhonny D. Cano -Leftware-
Be aware that Enum.Parse can be expensive. If you're on Compact Framework it's very expensive on each call, and if you're on full .NET then it can be expensive from a memory point of view (as stuff gets cached). So, this is the best answer but be careful about Enum.Parse.
Martin Peck
A: 

public void EnumInstanceFromString() {

 DayOfWeek wednesday = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "Wednesday");
 DayOfWeek sunday = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "sunday", true);
 DayOfWeek tgif = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "FRIDAY", true);

 lblOutput.Text = wednesday.ToString() +
                  ".  Int value = " + 
                  (int)wednesday).ToString() + "<br>";

 lblOutput.Text += sunday.ToString() + 
                   ".  Int value = " + 
                   ((int)sunday).ToString() + "<br>";

 lblOutput.Text += tgif.ToString() + 
                   ".  Int value = " + 
                   ((int)tgif).ToString() + "<br>";

 }
Vinay
+1  A: 
    enum test
    {
        VAL1,
        VAL2
    }

    static void Main(string[] args)
    {
        test newTest = (test)Enum.Parse(typeof(test), "VAL2");

        Console.WriteLine(newTest.ToString());
    }
cwap
beat me to it +1.
Cyril Gupta
A: 

Use this code...

BlahType blah = Enum.Parse(typeof(BlahType), "blahB");
Cyril Gupta
A: 

As stated above by a few others you would want to use:

        BlahType myEnum = (BlahType)Enum.Parse(typeof(BlahType), "blahB");
        int myEnumValue = (int)myEnum;
Alexander Kahoun