Enum Definition

suggest change

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

public enum MyEnum
{
    Monday = 1,
    Tuesday,
    Wednesday,
    //...
}

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 give each flag its own bit: explicit powers of two.

[Flags]
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 in binary as 00001001 (1 | 8). 

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
}

System.Enum derives from System.ValueType, so an enum value is passed by value. A call receives a copy of the underlying integral value (typically int), not a reference to a shared object. The value is boxed only when it is treated as object or a non-generic interface. See ValueType Class (System) (MSDN).

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents