C# Enumeration (Enum)
An enum is a set of named integer constants. The enum type is defined usingenumDeclared by keyword.
C# enums are value types. In other words, an enum contains its own values and cannot inherit or pass on inheritance.
DeclarationenumVariable
General syntax for declaring an enum:
enum <enum_name>
{
enumeration list
};
where,
- enum_nameSpecify the type name of the enum.
- enumeration listIs a comma-separated list of identifiers.
Each symbol in the enum list represents an integer value, one greater than the symbol before it. By default, the first enum symbol has a value of 0. For example:
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
Example
The following example demonstrates the usage of enum variables:
Example
using System;
public class EnumTest
{
enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
static void Main()
{
int x = (int)Day.Sun;
int y = (int)Day.Fri;
Console.WriteLine("Sun = {0}", x);
Console.WriteLine("Fri = {0}", y);
}
}
public class EnumTest
{
enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
static void Main()
{
int x = (int)Day.Sun;
int y = (int)Day.Fri;
Console.WriteLine("Sun = {0}", x);
Console.WriteLine("Fri = {0}", y);
}
}
When the above code is compiled and executed, it produces the following results:
Sun = 0 Fri = 5other extensions