What is Enums in C#?
enum (C# Reference) The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list. Enums in Csharp are Value data types.The enumerated type is declared using a keyword enum.
The syntax of enum
enum enum_name; { enumeration list constants };
enum_name – Name of the enumeration
enumeration list constants – List of enum constants. This will be comma-separated identifiers.
Example of enum in C#
public class EnumTest { enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; static void Main() { int x = (int)Days.Sun; int y = (int)Days.Fri; Console.WriteLine("Sun = {0}", x); Console.WriteLine("Fri = {0}", y); } } /* Output: Sun = 0 Fri = 5 */
How to enumerate enum in C#
The below example enumerates all the names or the constants that have been provided in the enum list.
using System; namespace EnumExample { class Program { enum MachineState { PowerOff = 0, Running = 5, Sleeping = 10, Hibernating = Sleeping + 5 } static void Main(string[] args) { //Enumerate the MachineStat enum foreach (MachineState item in Enum.GetValues(typeof(MachineState))) { Console.WriteLine(item); } Console.ReadLine(); } } } //Output of the MachineState enumeration is shown below: //PowerOff //Running //Sleeping //Hibernating
The below example enumerates all the Integer values of the enum MachineState
using System; namespace EnumExample { class Program { enum MachineState { PowerOff = 0, Running = 5, Sleeping = 10, Hibernating = Sleeping + 5 } static void Main(string[] args) { //Enumerate the MachineStat enum foreach (int item in Enum.GetValues(typeof(MachineState))) { Console.WriteLine(item); } Console.ReadLine(); } } } //Output: //0 //5 //10 //15
How to cast int to enum in C# and string to enum in C#
using System; namespace EnumExample { class Program { enum MachineState { PowerOff = 0, Running = 5, Sleeping = 10, Hibernating = Sleeping + 5 } static void Main(string[] args) { //Cast Enum From String Console.WriteLine((MachineState)Enum.Parse(typeof(MachineState), "PowerOff")); //Cast Enum from Integer Console.WriteLine((MachineState)15); Console.ReadLine(); } } } //Output: //PowerOff //Hibernating