C# Language Enum Enum basics

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!


From MSDN:

An enumeration type (also named an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable.

Essentially, an enum is a type that only allows a set of finite options, and each option corresponds to a number. By default, those numbers are increasing in the order the values are declared, starting from zero. For example, one could declare an enum for the days of the week:

public enum Day

That enum could be used like this:

// Define variables with values corresponding to specific days
Day myFavoriteDay = Day.Friday;
Day myLeastFavoriteDay = Day.Monday;

// Get the int that corresponds to myFavoriteDay
// Friday is number 4
int myFavoriteDayIndex = (int)myFavoriteDay;

// Get the day that represents number 5
Day dayFive = (Day)5;

By default the underlying type of each element in the enum is int, but byte, sbyte, short, ushort, uint, long and ulong can be used as well. If you use a type other than int, you must specify the type using a colon after the enum name:

public enum Day : byte 
    // same as before 

The numbers after the name are now bytes instead of integers. You could get the underlying type of the enum as follows:




Demo: .NET fiddle

Got any C# Language Question?