C# Enum | How To Play With Enum in C#?

In this article, we’ll talk about what exactly Enum is, and what are the best ways to use (enumeration) enum in C# with multiple examples.

C# Enum
C# Enum (enumeration type)

What is an enum (enumeration) in C#?

Definition: In C#, enum is a keyword that is used to create a set of integral named constants. In other words, we can say that an enumerated type in C# is declared using the enum keyword.

By default, the first item of an enum has started with the integer value 0, and the value of each successive enumerator is increased by 1.

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

 An enum is a great way to define a set of constant variables in a single data type. 

The syntax for declaring an enum

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

enum <Enum_Name> 
 {
   // Enumeration list 
 };

How to declare an Enum?

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 above code snippet, the “WorkingDays” enum declares the list of named constants in each line separated by a comma.

By default, the first item of an enum has started with the integer value 0. The second item has the value 1, and so on.

We can access the enum items with the dot operator as below.

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 GetValues() and GetNames() 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().

 GetValues(Type)  :

public static Array GetValues (Type enumType);

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

 GetNames(Type)  :

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 name?

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 enum.

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?

Retrieves an array of the values of the constants in a specified enumeration by using Enum.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();

        }

The following result will be print once we run the above program.

enum value result-shekh alI

Get an array and list of enum members

Let’s take a look on 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 we run the above program, we will get the following result.

enum to array and list
Example to convert enum to array and list

Why And When We Should Use Enum?

We can use enum when we have a set of values that aren’t going to change throughout the application, as days of week, months, seasons, colors, deck of cards, gender, conversion ratios for temperatures, time zones, and so on.

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 take a look on the following working example to understand it.

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
Enum.Parse method in C#

Convert Enum to string in C#

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

Let’s take a look on the following working example to understand it.

        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 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 or an integral 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

Advantage of using Enum in C#

    • Enums 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.
    • Enum or enumerations consumes less memory space as they are value type and allocated on the stack.
    • Enum simply provides a way of holding together a related group of more readable constants than magic numbers. We need to remember the real constants’ names rather than the integer values.
    • In C#, Enum can be declared inside or outside class and struct.
    • Flags attribute allows us to assign set multiple values to an enum object using a bitwise operator.
 Note:  In C#, a class can’t be derived from an enum because enum is treated as a sealed class and a sealed class can’t be inherited.

Summary:

In this article, we learned about the enum in C# with examples. The advantage of using Enums is that they are strongly typed constants that are very easy to use. Enums are represented as strings but processed as integers. Enums are easy to maintain and more readable to the user because they provide string named constants, which means we need to remember the names, not the 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.

Please let me know if you like this article.

Thanks for visiting 🙂

Leave a Reply