C# Language Keywords enum

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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

    // ...
}


Got any C# Language Question?