C# Enum | How to Use enumeration type in C#?

In this article, we will use some examples to explain what Enum is and how to best use Enum (or Enumeration) in C#.

Enum in C# is a value data type with a set of related named constants, commonly known as an enumerator list. The enum keyword is used to assign names or string values ​​to integer constants, making the program easy to read and maintain. Items in the enum can be declared in curly brackets {} separated by commas. It’s a user-defined primitive data type that can be integer, float, bytes, double, etc., but if you use it alongside int you will need to cast it. The underlying type of enumeration elements is int by default.

C# Enum
C# Enums

C# Enums

In C#, enum is a keyword used to create a set of integral named constants. In other words, we can say that an enumeration type is declared using the enum keyword in C#. By default, the first item in an enumeration (or enum) starts with the integer value 0, and the value of each subsequent enumerator is incremented by 1.

If no underlying type is explicitly declared for items in the enum, Int32 is used by default.
All the constant values in the enum can be declared inside the curly brackets { } separated by a comma “,”.

Enums in C # is a great way to define a set of constant (unchangeable/read-only) variables in a single data type.

Syntax to declare C# enumerations type

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

enum <Enum_Name> 
 {
   // Enumeration list 
 };

How to declare Enum in C#?

The enum keyword is used to declare new enumeration types in C#. The following is an example of an enum declaration.

public enum WorkingDays
{
  Monday,  // 0
  Tuesday, // 1
  Wednesday,  // 2
  Thursday, // 3
  Friday // 4
}

In the code snippet above, the “WorkingDays” enumeration declares a list of named constants on each line separated by commas. By default, the first element of the enum starts with the integer value 0. The value of the second element is 1, and so on.

Access an Enum

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

Advantage of using Enum in C#

    • Enums in C# are strongly typed constants which makes the code more readable to the user.
    • An enum is a great way to define a set of constant integral values to a single variable.
    • In C#, enums take up less space because they are value types and are allocated on the stack.
    • Enum just provides a way to group together a set of related constants that are more readable than magic numbers. We need to remember the names of real constants instead of integer values.
    • In C#, Enum can be declared inside or outside class and struct.
    • The Flags property allows us to assign multiple values ​​to enum objects using bitwise operators.

Note: In C#, A class cannot be derived from an enum because the enum is treated as a sealed class and a sealed class can not be inherited.

Enum methods in C#

As we know that the enum keyword is used to create enumeration in C#, whereas on the other hand, the Enum (Start with a capital letter) is the base class for enumerations, which contains the static methods called GetNames() and GetValues().

C# Enum.GetValues Method

public static Array GetValues (Type enumType);

The GetValues method returns an array that contains a value for each item in a specified enumeration.

Enum.GetNames Method

public static string[] GetNames (Type enumType);

The GetNames method returns a string array of the Names for each item (or constants) in the enum.

How to iterate an enum using Enum.GetNames methods?

Retrieves an array of the names of the constants in a specified enumeration by using Enum.GetNames method.

The Enum.GetNames() method requires the types of enum as input parameters, where we can pass using typeof keyword to retrieve an array of the names of the constants in the “Season” enumeration.

Let’s create a program to retrieve an array of names from a specified enumeration.

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)
        {
           //array of string
            string[] seasonNames = Enum.GetNames(typeof(Season));

            Console.WriteLine("*** Seasons Names ***");
            //iterate enum variables.
            foreach (var season in seasonNames)
            {             
                Console.WriteLine(season);
            }
                 Console.ReadKey();
        }
    }
}

We will get the following result after executing the above program.

enum GetNames

How to iterate an enum value using Enum.GetValues method ?

Retrieves an array of the values of the constants in a specified enumeration by using Enum.GetValues method. It returns an array containing the constant values ​​in enumType.

The following example illustrates the use of the GetValues method.

static void Main(string[] args)
        {
            //Reterieve value of each item in the enum.
            Array valueArray = Enum.GetValues(typeof(Season));

            //iterate valueArray.
            foreach (int enumValue in valueArray)
            {
                //Print Name and value of each item in the enum.
                Console.WriteLine($"Name: {Enum.GetName(typeof(Season), enumValue)}  Value: { enumValue}");
            }

            Console.ReadKey();

        }

As soon as we run the above program, the following result will be printed.

enum value result-shekh alI

Convert an enum to an array and 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();

        }
    }
}

As soon as we 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 optionally use 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 gets 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:

In the following example, Enum is used 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

Summary:

In this article, we got to know enumerations in C # using examples. The advantage of using enums is that they are strongly typed constants that are very easy to use. In C#, Enums are represented as strings but processed as integers. Enumerations are easier to manage and more readable for users because they provide constants with string names, which means we need to remember names, not integer values.

I hope you enjoyed this post and found it useful. In case you have any doubt, please post your feedback, question, or comments.

Recommended Articles

    1. Generic Delegates in C# With Examples
    2. IEnumerable Interface in C# with examples
    3. Constructors in C# with Examples
    4. 10 Difference between interface and abstract class In C#
    5. Properties In C# with examples
    6. C# Dictionary with Examples
    7. Multithreading in C#
    8. IEnumerable Interface in C# with examples
    9. C# List Class With Examples

Leave a Reply