.NET Framework Enum Definition


An enum is a special type of class. The enum keyword tells the compiler that this class inherits from the abstract System.Enum class. Enums are used for distinct lists of items.

public enum MyEnum
    Monday = 1,

You can think of an enum as a convenient way of mapping constants to some underlying value. The enum defined above declares values for each day of the week, and starts with 1. Tuesday would then automatically become mapped to 2, Wednesday to 3, etc.

By default, enums use int as the underlying type and start at 0, but you can use any of the following integral types: byte, sbyte, short, ushort, int, uint, long, or ulong, and can specify explicit values for any item. If some items are explicitly specified, but some are not, each item after the last defined one will be incremented by 1.

We would use this example by casting some other value to a MyEnum like so:

MyEnum instance = (MyEnum)3; // the variable named 'instance' gets a 
                             //value of MyEnum.Wednesday, which maps to 3.

int x = 2;
instance = (MyEnum)x; // now 'instance' has a value of MyEnum.Tuesday

Another useful, although more complex, type of enum is called Flags. By decorating an enum with the Flags attribute, you can assign a variable more than one value at a time. Note that when doing this you must define values explicitly in base 2 representation.

public enum MyEnum
    Monday = 1,
    Tuesday = 2,
    Wednesday = 4,
    Thursday = 8,
    Friday = 16,
    Saturday = 32, 
    Sunday = 64

Now you can compare more than one value at a time, either using bitwise comparisons or, if you are using .NET 4.0 or later, the built-in Enum.HasFlag method.

MyEnum instance = MyEnum.Monday | MyEnum.Thursday; // instance now has a value of
                                                   // *both* Monday and Thursday,
                                                   // represented by (in binary) 0100. 

if (instance.HasFlag(MyEnum.Wednesday))
    // it doesn't, so this block is skipped
else if (instance.HasFlag(MyEnum.Thursday))
    // it does, so this block is executed

Since the Enum class is subclassed from System.ValueType, it is treated as a value type and passed by value, not by reference. The base object is created on the heap, but when you pass an enum value into a function call, a copy of the value using the underlying value type of the Enum (typically System.Int32) is pushed onto the stack. The compiler tracks the association between this value and the base object that was created on the stack. See ValueType Class (System) (MSDN) for more information.