Divakar
Divakar

Reputation: 672

Retrieving integer values from an enum

I have defined an enum and tried to retrieve it as follows

class Demo
{
    enum hello
    { 
        one=1,
        two
    }

    public static void Main()
    {           
        Console.WriteLine(hello.one);            

        Console.ReadLine();
    }
}

Now, how do i retrieve the integer value "1" from the enum ?

Upvotes: 0

Views: 114

Answers (4)

SeeSharp
SeeSharp

Reputation: 179

you can cast the enums like

int a = (int)hello.one

Upvotes: 1

Neeraj
Neeraj

Reputation: 4489

Try This.

Console.Writeline((int)hello.Value);

or

int value = Convert.ToInt32(hello.one);

Upvotes: 0

V4Vendetta
V4Vendetta

Reputation: 38230

Well you can do a cast to int

Console.WriteLine((int)hello.one);

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503180

There's an explicit conversion from any enum type to its underlying type (int in this case). So:

Console.WriteLine((int) hello.one);

Likewise there's an explicit conversion the other way:

Console.WriteLine((hello) 1); // Prints "one"

(As a side note, I'd strongly advise you to follow .NET naming conventions, even when writing tiny test apps.)

Upvotes: 3

Related Questions