Lesson #24 - Working with Enums

An enum is a type of class that represents a group of “Read-Only” variables that cannot be inherited or inherit from other classes. To create an enum we will use the ‘enum’ keyword 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)

}

}

}




2 views0 comments