C# Enums

In C#, an enum is a user-defined type that consists of a set of named constants, known as the enumerator list. Enums provide a convenient way to define a set of named integral constants that can be used throughout your code.

Syntax

The syntax for defining an enum in C# is as follows:

1enum EnumName 2{ 3 value1, 4 value2, 5 value3, 6 ... 7}

Here, EnumName is the name of the enum, and value1, value2, value3, etc. are the named constants or enumerators.

Example

Let's say we want to define an enum for the days of the week. We can do it like this:

1enum DayOfWeek 2{ 3 Monday, 4 Tuesday, 5 Wednesday, 6 Thursday, 7 Friday, 8 Saturday, 9 Sunday 10}

Now, we can use this enum to represent the days of the week in our code. For example:

1DayOfWeek today = DayOfWeek.Monday; 2Console.WriteLine("Today is " + today);

This will output: Today is Monday

Enum Underlying Type

By default, enums in C# are based on the int type, and the first enumerator has a value of 0. However, you can specify a different underlying type for the enum by specifying it explicitly:

1enum EnumName : underlyingType 2{ 3 ... 4}

Here, underlyingType can be any integral type, such as byte, sbyte, short, ushort, int, uint, long, or ulong.

Example

Let's say we want to define an enum for the months of the year, and we want each enumerator to have a value that corresponds to the month number. We can do it like this:

1enum MonthOfYear : byte 2{ 3 January = 1, 4 February, 5 March, 6 April, 7 May, 8 June, 9 July, 10 August, 11 September, 12 October, 13 November, 14 December 15}

Here, we have specified the underlying type as byte, and we have given each enumerator a value that corresponds to the month number.

Now, we can use this enum to represent the months of the year in our code. For example:

1MonthOfYear month = MonthOfYear.June; 2Console.WriteLine("The month is " + month); 3Console.WriteLine("The month number is " + (byte)month);

This will output:

1The month is June 2The month number is 6