C# Enum: How to use enumeration type in C#?

What is an enum in C#?

An enum, or enumeration, is a value type in C# that consists of a set of named constants called the members of the enum. Enums are useful when you have a fixed set of values that a variable can take on, such as the days of the week or a set of predefined options.

Enums are value types, so they are stored in the stack rather than the heap. This means that they are faster to access than reference types, but they also take up more memory.

In this post, we will learn the proper usage of an enum in c# with multiple examples.

C# Enum
C# Enums

Advantages to using enums in C#

There are several advantages to using enums in C#:

  • Enums can make your code more readable and easier to understand. By giving meaningful names to a set of predefined values, you can make it clearer what the values represent and how they should be used.
  • Enums can help prevent errors. By limiting the values that a variable can take on to a predefined set, you can ensure that only valid values are used. This can help prevent issues caused by using invalid or unexpected values.
  • Enums can improve the performance of your code. Because they are value types, enums are stored in the stack rather than the heap, which means they are faster to access than reference types.
  • Enums can make your code more maintainable. By using enums, you can centralize the definitions of your predefined values in a single location, which makes it easier to make changes or add new values in the future.
  • Enums can be used in switch statements. Because enums have a fixed set of values, you can use them in a switch statement to create more efficient code that is easier to read and maintain.
  • Enums can be declared inside or outside the class and struct.
  • The Flags property allows us to assign multiple values ​​to enum objects using bitwise operators.

Overall, enums are a useful feature in C# that can help improve the readability, maintainability, and performance of your code.

Syntax

The following is the syntax for defining an enum in C#.

enum <Enum_Name> 
 {
   // Enumeration list 
 };

Define Enum in C#

The enum keyword is used to declare new enumeration types in C#. Here is an example of how you can define an enum in C#:

public enum DaysOfWeek
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

In the above example, the DaysOfWeek enum has seven members: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday. These members are assigned default values of 0, 1, 2, 3, 4, 5, and 6, respectively. However, you can also specify custom values for the members of an enum:

Example:

public enum Season
{
    Winter = 1,
    Spring = 2,
    Summer = 3,
    Fall = 4
}

In the above code example, the Season enum has four members: Winter, Spring, Summer, and Fall. These members are assigned values of 1, 2, 3, and 4, respectively.

Once you have defined an enum, you can use it in your code like this:

DaysOfWeek today = DaysOfWeek.Monday;
Season currentSeason = Season.Spring;

C# Enum in Switch Statement

You can also use an enum in a switch statement:

switch (today)
{
    case DaysOfWeek.Monday:
        Console.WriteLine("It's Monday!");
        break;
    case DaysOfWeek.Tuesday:
        Console.WriteLine("It's Tuesday!");
        break;
    // and so on..
}

Define Enum Inside a Class

Enums defined within a class are only visible and accessible within the class and its nested types. They are not accessible from outside the class.

To define an enum inside a class in C#, you can use the following syntax:

public class MyClass
{
    public enum MyEnum
    {
        Value1,
        Value2,
        Value3
    }
}

You can then use the enum within the class like this:

MyClass.MyEnum enumValue = MyClass.MyEnum.Value2;

Enum Values

An enum value is a named constant that is a member of an enumeration. Enum values are used to represent a set of predefined options or states.

In C#, you can define an enum like this:

public enum MyEnum
{
    Value1,
    Value2,
    Value3
}

This enum has three values: Value1, Value2, and Value3. By default, these values are assigned integer values starting at 0 and incrementing by 1 for each subsequent value. So in this example, Value1 would have a value of 0, Value2 would have a value of 1, and Value3 would have a value of 2.

You can also specify custom values for the enum values:

public enum MyEnum
{
    Value1 = 10,
    Value2 = 20,
    Value3 = 30
}

In the above code example, Value1 would have a value of 10, Value2 would have a value of 20, and Value3 would have a value of 30.

You can use an enum value in your code like this:

MyEnum myValue = MyEnum.Value3;

Let’s use an enum value in a switch statement:

switch (myValue)
{
    case MyEnum.Value1:
        Console.WriteLine("Value1");
        break;
    case MyEnum.Value2:
        Console.WriteLine("Value2");
        break;
    case MyEnum.Value3:
        Console.WriteLine("Value3");
        break;
}

Enum values are useful when you have a fixed set of options or states that a variable can hold, and you want to give those options meaningful names. They can make your code easier to read and understand, and can also help prevent errors by ensuring that only valid values are used.

How to access an Enum item?

You can use dot (.) syntax to access enumerations: enum.member

using System;
namespace EnumExample
{
    
    class Program
    { 
      // Declaring an enum inside a class
       
        public enum WorkingDays
        {
            Monday,  // 0
            Tuesday, // 1
            Wednesday,  // 2
            Thursday, // 3
            Friday // 4
        }

        static void Main(string[] args)
        {
          // Accessing enum item using dot (.) operator
            WorkingDays workingDays = WorkingDays.Monday;
            Console.WriteLine($"WorkingDay : {workingDays}");
            Console.ReadKey();
        }
    }
}
// Output:
//WorkingDay : Monday

Enum methods in C#

There are several methods that are available for working with enums in C#. These are just a list of a few of the methods that are available for working with enums in C#. Enums are a powerful and useful feature of the language, and these methods provide a convenient way to work with them in your code.

01. Enum.GetValues(): This method returns an array of all the values in an enum.

using System;
namespace EnumExample
{
    public enum MyEnum
    {
        Value1,
        Value2,
        Value3
    }
    public class program
    {
        public static void Main()
        {   
            // Getting values
            MyEnum[] values = (MyEnum[])Enum.GetValues(typeof(MyEnum));
            // Printing enum values
            foreach(var item in values)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();
        }
    }
}

02. Enum.GetNames(): This method returns an array of strings containing the names of all the values in an enum.

string[] names = Enum.GetNames(typeof(MyEnum));

03. Enum.Parse(): This method converts a string to an enum value.

MyEnum myValue = (MyEnum)Enum.Parse(typeof(MyEnum), "Value2");

04. Enum.ToObject(): This method converts an integer to an enum value.

MyEnum myValue = (MyEnum)Enum.ToObject(typeof(MyEnum), 1);

05. Enum.GetUnderlyingType(): This method returns the underlying type of an enum (i.e., the type of the values in the enum).

Type underlyingType = Enum.GetUnderlyingType(typeof(MyEnum));

How to convert an enum to an array or List in C#?

Let’s take a look at the following working example to convert an enum to an array and List.

using System;
using System.Collections.Generic;
using System.Linq;
namespace EnumExample
{
    
    class Program
    {  // Declared an enum inside a class
       public enum Months
        {
            January,
            February,
            March,
            April,
            May,
            June,
            July
        }

        static void Main(string[] args)
        {
            // Example 1: Get array of enum constants
            Console.WriteLine("**** Get array of enum constants using Enum.GetValues method ****");
            Months[] months = (Months[])Enum.GetValues(typeof(Months));
            Console.WriteLine(string.Join(Environment.NewLine,months));

            Console.WriteLine("**** Get List of enum constants using LINQ ****");
           // Example 2: Get List of enum constants using LINQ
           List <Months> monthList = Enum.GetValues(typeof(Months))
                            .Cast<Months>()
                            .ToList();

            Console.WriteLine(string.Join(Environment.NewLine, monthList));

            Console.ReadKey();

        }
    }
}

Once you run the above program, the following result will be printed.

Convert enum to array and list
Example to convert enum to array and list in C#

Why and when should you use Enums in C#?

When we have a set of values ​​that will not change throughout the application, we can use enumerations, such as days of the week, months, seasons, colors, deck of card, gender, time zones, temperature conversion ratios, etc.

How to Parse a string to Enum in C#

To convert string to enum we can simply use the static method  Enum.Parse . The first parameter of this method is an enum type, the second parameter is a string type, and the third parameter takes a boolean value which is optionally used to ignore the case.

Let’s look at the following working example to understand.

using System;
namespace EnumExample
{
    
    class Program
    {  // Declared an enum inside a class
        enum Season
        {
            Spring = 1,
            Summer = 2,
            Autumn = 3,
            Winter = 4
        }

        static void Main(string[] args)
        {   // String value
            string winter = "Winter";
           
            //Convert string to enum
            Season season = (Season)Enum.Parse( typeof(Season), winter,true);
            if(season is Season.Winter)
            {
                Console.WriteLine($"Season : {season}");
            }

            Console.ReadKey();

        }
    }
}
// Output:
//Season : Winter
Enum.Parse method in C#
Parse a string to Enum in C# using Enum.Parse method

How to Convert an Enum to string in C#?

To convert an enum to a string, we can simply use  ToString()  method.

Let’s look at the following working example to understand.

        static void Main(string[] args)
        {
            //Get enum
            Season season = Season.Summer;

            //Example 1: Convert enum to string value
            string summer = season.ToString();
            Console.WriteLine($"Season : {summer}");

            //Example 2: Convert enum to string value
            Console.WriteLine($"Season : {Season.Winter.ToString()}");

            Console.ReadKey();

        }
// Output:
// Season : Summer
// Season : Winter

Get enum by the number value

The Enum.GetName method is used to get the name of an enum value. Let’s look into the following code snippet to get the name of the 2nd element of the “Season” enum.

static void Main(string[] args)
        {         
            // Get name of 2nd value in Season enum  
            string season = Enum.GetName(typeof(Season), 2);
            Console.WriteLine($"Season: {season}");

            Console.ReadKey();

        }
// Output:
// Season: Summer

Flag Attribute in C# Enums

The Flags attribute in enum is used to represent a collection of possible values, rather than a single value.
We can use the [Flag] attribute when we want to set multiple values to an enum. Such collections are often used with the switch & bitwise (OR |) operators, for example.

using System;

namespace EnumExample
{
    // Using Flag Attribute in enum
    [Flags]
    enum Colors
    {
        //We must use powers of two for bitwise operations to work
        Red =  1,

        Green  =  2,

        Blue   =  4,

        Yellow =  8
    };

    class Program
    {  

        static void Main(string[] args)
        {
            // Using bitwise ( OR  | ) operator.
            Colors allowedColors = Colors.Blue | Colors.Red;

            string[] colors = Enum.GetNames(typeof(Colors));
            foreach (var name in colors)
            {
                var color = (Colors)Enum.Parse(typeof(Colors), name);
                if (allowedColors.HasFlag(color))
                 Console.WriteLine($"{color} Color is allowed.");
                else
                 Console.WriteLine($"{color} Color is not allowed.");               
            }
                Console.ReadKey();
            }         
        }
    }
enum flag example
Flag example in enum.

Check if a string value is defined in an Enum

By using  Enum.IsDefined method, We can check if a given string named constant or an integral value exists in a specified enum.

class Program
    {

        static void Main(string[] args)
        {  
            //check if integral value exists in an existing enum
            Console.WriteLine(Enum.IsDefined(typeof(Colors), 0));

            //check if string named constant exists in an existing enum
            Console.WriteLine(Enum.IsDefined(typeof(Colors), "Blue"));

            Console.ReadKey();
        }
    }
    // Output:
    // False
    // True

C# Enum in a Switch Statement

In C #, enums are commonly used in switch statements to verify the corresponding values:

The following is an example to use an enum in a switch statement.

using System;
namespace EnumInSwitchStatement
{
    public enum Operator
    {
        // List of operators
        PLUS,
        MINUS,
        MULTIPLY,
        DIVIDE
    }

    public class Program
    {
        public double Calculate(int leftValue, int rightValue, Operator op)
        {
            switch (op)
            {
                case Operator.PLUS: return leftValue + rightValue;
                case Operator.MINUS: return leftValue - rightValue;
                case Operator.MULTIPLY: return leftValue * rightValue;
                case Operator.DIVIDE: return leftValue / rightValue;
                default: return 0.0;
            }
        }

        public static void Main()
        {
           
            Console.WriteLine("** Example - Enum inside a switch statement in C# ** \n");
            Program program = new Program();
            Console.WriteLine($"The sum of 10 + 10 is { program.Calculate(10, 10, Operator.PLUS)}");
            Console.ReadKey();
        }
    }
}
Enum inside a switch statement in CSharp
Enum inside a switch statement in CSharp

Q: Why is an enum used in C#?

Enums are used in C# to represent a set of predefined values or states. They can make your code more readable and maintainable by giving meaningful names to a fixed set of values, and they can help prevent errors by ensuring that only valid values are used. Enums can also improve the performance of your code by being stored in the stack rather than the heap. Overall, enums are a useful feature of C# that can help improve the readability, maintainability, and performance of your code.

Q: Can an enum be null in C#?

Ans: Enum types cannot contain null values.

Q: Can an enum be static in C#?

Ans: An enum can’t be static in C#.

Q: Are enums in C# immutable?

Ans: Enum values are intended to be immutable and typically describe the type or status of something, so they don’t frequently change what they mean.

Q: How do you use enums?

Ans: When a variable (particularly a method parameter) can only accept one value out of a limited set of options, you should always use enums.
Examples would be things like type constants (Directions: “NORTH”, “SOUTH”, “EAST”, “WEST”)

I hope this post was useful and enjoyable for you. If you have any questions or feedback, please leave a comment below.

References: MSDN-Enumeration types

Recommended Articles:

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments