Blankman
Blankman

Reputation: 267150

casting an enumeration to get the value associated with it?

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?

Upvotes: 0

Views: 600

Answers (6)

cwap
cwap

Reputation: 11287

enum test
{
   VAL1,
   VAL2
}

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

Upvotes: 1

Alexander Kahoun
Alexander Kahoun

Reputation: 2488

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

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

Upvotes: 0

Jhonny D. Cano -Leftware-
Jhonny D. Cano -Leftware-

Reputation: 18013

Use:

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

and then

int yourIntValue = (int) yourEnumValue;

Upvotes: 5

Cyril Gupta
Cyril Gupta

Reputation: 13723

Use this code...

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

Upvotes: 0

Vinay
Vinay

Reputation: 4793

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>";

 }

Upvotes: 0

Jakob Christensen
Jakob Christensen

Reputation: 14956

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

Upvotes: 1

Related Questions