tags:

views:

285

answers:

5
 public Enum Days
 {
    Monday = 1,
    Tuesday = 2,
    Wednesday = 3,
    Thursday = 4,
    Friday = 5,
    Saturday = 6,
    Sunday = 7
 }

Now I wanted to know how do I get the integer value of an enum and convert an integer value into enum

Will

       int dayNo = (int) Days.Monday;

change the value of dayNo to 1;

and

Will

        Days day = (Days) 2;

assign Days.Tuesday to the variable day ??

How about is this the best way to do the parsing??

+1  A: 

Yes it will. But did you try it before posting?

David M
+4  A: 

In a word, yes.

acron
+2  A: 

Your understanding of enums is correct.

You can use Enum.Parse to convert from number/name to enum type if you feel more comfortable with this method, but it gains nothing in readbility or performance.

Strangely, in order to parse numbers, you need to call ToString() on them first, as Enum.Parse has no integer overload.

From the MSDN page:

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
Oded
thank you i just wanted to know if there was another way of doing the above except when parsing.
soldieraman
`Enum.Parse` does NOT convert from an `int` to the appropriate `enum` value. This answer is wrong or misleading at best.
Jason
@Jason - Going by the documentation, it does convert to an equivalent enumerated object.
Oded
A bit of a hair spliter, it will parse from a string rep of the int.Days x = (Days)Enum.Parse(typeof(Days), "3"); orDays y = (Days)Enum.Parse(typeof(Days), 3.ToString()); but not the int itself. http://stackoverflow.com/questions/2139420/enum-to-int-int-to-enum-best-way-to-do-conversion/2139465#2139465
runrunraygun
@Oded: But there is no overload of `Enum.Parse` that has a parameter of type `int`.
Jason
@Jason - You are right and the documentation seems to be misleading. As you say, you need to call `ToString()` on an integer in order to use `Enum.Parse`.
Oded
+7  A: 

Yes, and this is very easy to check:

Days d = (Days)3;
Console.WriteLine(d);

This will output

Wednesday

As a best practice, the name of your enum should be Day not Days; the variable d above represents a Day not Days. See the naming guidelines on MSDN.

Jason
+2  A: 

Yes it will do exactly that except Enum should be enum

public enum Days
 {
    Monday = 1,
    Tuesday = 2,
    Wednesday = 3,
    Thursday = 4,
    Friday = 5,
    Saturday = 6,
    Sunday = 7
 }

To use Enum.Parse you MUST provide a string so if you want to cast from the int you'd have to go via a string which is ugly.

Days x = (Days)Enum.Parse(typeof(Days), "3");
Days y = (Days)Enum.Parse(typeof(Days), 3.ToString());

... both give you wednesday.

runrunraygun