Enumerations
Defines what enumerations are and how it is used in a C# program
In developing an application, we may find a situation in which we want to have a variable that can take a value from a given set of values. For example, we might need a variable for storing the weekday or month name. Enumerations can be used in such situations. Enumerations create the definition of a data-type that can take one of a given set of values.
Enumerations are defined using the enum keyword. The structure is:
enum Data-typename : base-type
{
value1,
value2,
...
last value
}
Here, the base-type can be byte, sbyte, short, ushort, int, uint, long, and ulong.
We need to declare a variable of this new Data-type name as:
Data-Typename variable;
To understand this, let us create an actual enumeration:
namespace AdvCsharp
{ enum weekday : int { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
class Program { static void Main(string[] args)
{
weekday myday = weekday.Sunday;
Console.WriteLine("Hello, today is {0}", myday);
}
}
}
The first thing to note here is the location of the enumeration declaration. Unlike the programs we have made so far, the enumeration is not declared inside the Main method but outside it.
The name of the enumeration is `weekday'. This makes `weekday' a data-type. The base type of the enumeration is integer (int). This implies that the first value of the enumeration (Sunday) is represented by the value 0, Monday by 1 and so on.
Inside the Main method, we have created a variable `myday' of the type `weekday' and assigned it one of the enumeration values. The output statement is used to display the value of this variable. If we execute this program, we will get the following output:
Hello, today is Sunday