How to use Enum in C#

Enums in C# are a way to define a set of strongly typed constants. They are useful when you have a collection of constants that are logically related to each other. By grouping these constants together in an enumeration, you can refer to them in a consistent, expressive, and type-safe manner. This provides several benefits, including improved code readability, better code organization, and enhanced type safety during compilation.

Syntax
enum<enum_name> { enumartion list }
Creating an enumeration type
enum Tempurature { Low, Medium, High, };

Enums in C# serve as strongly typed constants that contribute to improved code readability and reduced error susceptibility. They are particularly useful when you have a fixed set of functionally significant values that are unlikely to change. The main advantage of using enums is their ability to facilitate future value modifications with ease, ensuring consistency and minimizing errors caused by numerical transposition or typographical mistakes. By providing a clear and intuitive representation of these values, enums enhance code maintainability and robustness.

How to retrieve enum values

Temperature value = Tempurature.Medium; if (value == Tempurature.Medium) { Console.WriteLine("Temperature is Mediuam.."); }
example
using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } enum Tempurature { Low, Medium, High, }; private void button1_Click(object sender, EventArgs e) { Temperature value = Tempurature.Medium; if (value == Tempurature.Medium) { MessageBox.Show ("Temperature is Mediuam.."); } } } }

By default the underlying type of each element in the enum is int. If you try with above example to convert to integer then you can see the result:

Temperature value = Tempurature.Medium; int val = (int)value; Console.WriteLine("Temperature value is.." + val);
output
Temperature value is..1

Enum underlying type

By default, the underlying type of each element in an enum is int in C#. This implies that if an enum declaration does not explicitly specify an underlying type, it will automatically default to int. However, you have the flexibility to specify a different integral numeric type by utilizing a colon and explicitly declaring the desired underlying type. C# allows you to explicitly assign an underlying type of byte, sbyte, short, ushort, int, uint, long, or ulong to an enum, depending on the specific requirements of your application.

The following Enum declare as byte, you can verify the underlying numeric values by casting to the underlying type .

enum Temperature : byte { Low, Medium, High, };

You can retrieve the value like the following:

Temperature value = Temperature.Medium; byte val = (byte)value; Console.WriteLine("Temperature value is.." + val);
output
Temperature value is..1

Enum values

You have the flexibility to assign custom values to the elements within an enum. By default, the first member of an enum is assigned a value of zero. However, if this value is not appropriate for your specific enum, you have the option to assign it a different value, such as one or any other desired number. When a different value is declared for the first member, the subsequent members of the enum are automatically assigned values that increment by one from the value of the preceding member. This allows you to define a meaningful and sequential set of values for your enum elements.

enum Tempurature { Low = 2, Medium, High, }; Temperature value = Tempurature.Medium; int val = (int)value; Console.WriteLine("Temperature value is.." + val);
output
Temperature value is.. 3

How to cast an Enum directly to int?

enum Days { Sunday = 1, TuesDay = 2, wednesday=3 } //get value int day = (int)Days.TuesDay;

How to cast int to enum?

Method 1:

Following is the easiest method to cast an int to enum.

MyEnum myenum = (MyEnum)intvalue;
example
enum Days { Sunday = 1, TuesDay = 2, wednesday=3 } //cast to enum Days day = (Days)3;

Converts int to enum values

Method 2:
MyEnum myenum = (MyEnum)Enum.ToObject(typeof(MyEnum) , intvalue);
example
Days day = (Days)Enum.ToObject(typeof(Days), 3);

How to check If a Enum contain a number?

The Enum.IsDefined() method tests if a particular value or name is defined within an enumeration's list of constants.

Enum.IsDefined(Type, Object)

This method requires two parameters. The first one is the type of the enumeration to be checked. This type is usually obtained using a typeof expression . The second one is defined as a basic object. It is used to specify either the integer value or a string containing the name of the constant to find. The return value is a Boolean that is true if the value exists and false if it does not.

using System; using System.Windows.Forms; namespace WindowsFormsApplication4 { enum Status { start =0, stop=1 }; public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click_1(object sender, EventArgs e) { bool ifExists; // Testing for Integer Values ifExists = Enum.IsDefined(typeof(Status), 0); // exists = true ifExists = Enum.IsDefined(typeof(Status), 2); // exists = false // Testing for Constant Names ifExists = Enum.IsDefined(typeof(Status), "start"); // exists = true ifExists = Enum.IsDefined(typeof(Status), "run"); // exists = false } } }

Enum.Parse

Enum.Parse() converts the C# string representation of the name or integer value of one or more enumerated constants to an equivalent Enum object .

Convert a string to an enum
using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public enum Colors { red, blue, green, yellow } private void button1_Click(object sender, EventArgs e) { string inVal = "green"; Colors newColor = (Colors)Enum.Parse(typeof(Colors), inVal); //Check the Enum type if (newColor == Colors.green) { MessageBox.Show(newColor.ToString()); } } } }
output
green

How to Loop through all enum values

The Enum.GetValues() method returns an array that contains a value for each member of the enum Type . If more than one members have the same value, it returned array includes duplicate values

Iterating through an enum

The following example will show how do enumerate an enum .

using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public enum Colors { red, blue, green, yellow } private void button1_Click(object sender, EventArgs e) { foreach (Colors iColor in Enum.GetValues(typeof(Colors))) { MessageBox.Show(iColor.ToString()); } } } }

Enum in Switch Case

The following program shows how to use Enum in Switch..Case statement.

using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } enum Tempurature { Low, Medium, High, }; private void button1_Click(object sender, EventArgs e) { Temperature value = Tempurature.Medium; switch (value) { case Tempurature.Low: MessageBox.Show("Low Tempurature"); break; case Tempurature.Medium: MessageBox.Show("Mediuam Tempurature"); break; case Tempurature.High: MessageBox.Show("High Tempurature"); break; } } } }

Enum Class Methods

Methods Description
Equals(Object) Returns a boolean value indicating whether this instance is equal to a specified object.
GetNames(Type) Retrieves string array of the names of the constants in in enumType.
HasFlag(Enum) Returns true one or more bit fields are set in the current instance.
Parse(Type, String) Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
ToString() Returns the string representation of the value of this instance.

Conclusion

C# enum is a feature that allows you to define a set of named constants, providing more readability and type safety to your code. By default, enums have an underlying type of int, but you can specify a different integral type if needed.