enum

suggest change

The enum keyword declares a value type derived from System.Enum, which itself derives from ValueType. Use it for a distinct set of named constants.

public enum DaysOfWeek
{
    Monday,
    Tuesday,
}

You can optionally specify a specific value for each one (or some of them):

public enum NotableYear
{
   EndOfWwI = 1918,
   EndOfWwII = 1945,
}

This example omits a value for 0, which is usually a bad practice. The default value of an enum is (YourEnumType)0. If no member has that value, a new variable is not one of the named constants.

The default underlying type of an enum is int. It can be byte, sbyte, short, ushort, int, uint, long, ulong, or char. This enum uses byte:

enum Days : byte
{
    Sunday = 0,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
};

Also note that you can convert to/from underlying type simply with a cast:

int value = (int)NotableYear.EndOfWwI;

For these reasons you’d better always check if an enum is valid when you’re exposing library functions:

void PrintNotes(NotableYear year)
{
    if (!Enum.IsDefined(typeof(NotableYear), year))
        throw new InvalidEnumArgumentException("year", (int)year, typeof(NotableYear));

    // ...
}

Feedback about page:

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



Table Of Contents