Essential C# Keywords  Suggest an edit

enum

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));

    // ...
}


Table Of Contents
22 Enum
25 GUID
52 Keywords
107 Stream
108 Timers
  ↑ ↓ to navigate     ↵ to select     Esc to close