Friday, May 7, 2010

Enums

I received an email from a former co-worker asking about enums and I thought this would be a good quick entry for today.

The question was, what is the difference between the following two enum declarations:
a.  public enum Genders { Male, Female };
b.  public enum Genders : int { Male, Female };

The answer, in this case, is there is no difference!  The reason is by default an enumeration's underlying data type is an int.

However, the underlying type can be changed to any integral type except a char. So byte, long, etc...

But, you'll have to cast your enum value to that type to get the data out

Ex. (this is from Microsoft's MSDN site)

enum Range : long { Max = 2147483648L, Min = 255L };

long x = (long)Range.Max;


Enums are also 0-based indexes by default. So the first position (Male) will be "0" in both of these cases.

You can change the starting index number by setting the value of the first item in the enum:

public enum Genders { Male = 1, Female};

Now, Male will be 1 and Female will be 2.  And as you guessed if you had a NotSpecified then it would be 3.

Lastly, you can set your own enum values as well.

public enum FoodRanking { Mexican = 1, Brazilian = 6, Italian = 2, American = 3, German = 4, French =5};

**Notice, your values don't have to be in order.

No comments:

Post a Comment