0

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 ?

0

4 Answers 4

3

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

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

2 Comments

Console.WriteLine((hello) 1); doesnt print "one". It prints "1" right ?
@DivakarRaj: No, it prints "one" because it's calling ToString on the enum value - it's like printing hello.one.
1

you can cast the enums like

int a = (int)hello.one

Comments

0

Well you can do a cast to int

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

1 Comment

guess i was 4 sec too late :(
0

Try This.

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

or

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

Comments

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.