enum

Download c# eBook

Example

The enum keyword tells the compiler that this class inherits from the abstract class Enum, without the programmer having to explicitly inherit it. Enum is a descendant of ValueType, which is intended for use with 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;
   EnfOfWwII = 1945,
}

In this example I omitted a value for 0, this is usually a bad practice. An enum will always have a default value produced by explicit conversion (YourEnumType) 0, where YourEnumType is your declared enume type. Without a value of 0 defined, an enum will not have a defined value at initiation.

The default underlying type of enum is int, you can change the underlying type to any integral type including byte, sbyte, short, ushort, int, uint, long and ulong. Below is an enum with underlying type 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 InvalidEnumArgumentException("year", (int)year, typeof(NotableYear));

    // ...
}

Stats

Contributors: 3
2016-07-26
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook