C# enum example.
In this tutorial we learn about enum in C#
Enum is a value type in .net data type, Enum is an abstract class that has some static methods to work with enum.
Before we see some enum example, let's take a look at the methods of System.Enum.
Gets the name of the constant in the specified enumeration
Returns a string array of constant names
Returns an array of constant values
This is how you can create a enum in C#, you can declare a enum as protected, private, public
enum EventState { Initiated = 1, Started = 2, Closed = 3, Canceled = 4 }
Enum GetNames Example
Here we see how to use enum (enumeration) in our c# code
foreach (string str in Enum.GetNames(typeof(EventState))) { Console.WriteLine(str); }
foreach (int i in Enum.GetValues(typeof(EventState))) { Console.WriteLine(i); }
//this will print the number 2 Console.WriteLine((int)EventState.Started); // this will print string "Started" Console.WriteLine(EventState.Started); }
You can define a enum in c# as Array Index
enum ColorSignal { red, white, blue, green, yellow, orange, grey }
Now we write an C# program with an array that is indexed with enum values. here you notice how to cast an enum to an int.
void EnumTest() { int[] _array = new int[(int)ColorSignal.white]; }
we can iterate or loop through an enum items using foreach loop or for loop, take a look at example below
foreach (string s in Enum.GetNames(typeof(ColorSignal))) { Console.WriteLine(s); }
we can also read value from enum like this way
Console.WriteLine(ColorSignal.green); // this will print string value - green Console.WriteLine((int)ColorSignal.green); // this will print int value - 3
we can pass C# enum as parameter in any method, and we can that enum as string, also can get the enum integer value, take a look at the example below.
public void AddColor(ColorSignal color) { Console.WriteLine(color.ToString()); // orange Console.WriteLine(color); // orange Console.WriteLine((int)color); // 6 } // call the method and pass enum as parameter AddColor(ColorSignal.orange);
You may also check How to convert enum to generic list type