C# Tutorial For Beginners: Working with Enums
Updated: Jan 19, 2022
An Enum is a class that represents a group of “Read-Only” variables that cannot be inherited or inherited from other classes. We will use the ‘Enum’ keyword to create an Enum and separate its value with a comma. Here is a general syntax for declaring it:
namespace the_enum
{
//Creating the Enum
enum Colors{ blue = 1, green = 2, yellow = 3}
class Program
{
static void Main(string[] args)
{
Colors enumValue = Colors.blue;
Console.WriteLine(enumValue);
Console.WriteLine(Colors.yellow);
/*Output:
blue
yellow
*/
}
}
}
Enum Values
The enum is similar to a collection where each element has its value. By default, the first item has the value (And so on…). To get this value, you must Explicitly cast the enum to int:
namespace the_enum
{
//Creating the enum
enum Colors{ blue = 1, green, yellow = 7}
class Program
{
static void Main(string[] args)
{
int enumValue;
Console.WriteLine(enumValue =Convert.ToInt32(Colors.yellow));//Return the value of '7'
Console.WriteLine(enumValue = Convert.ToInt32(Colors.green));//Return the value of '2'(Default Value)
}
}
}