C# - Enums (Enumerations)



An enumeration (enum) is a special value type which defined set of named integer constants. An enumerated type is declared using the enum keyword.

C# enumerations are value data type. In other words, enumeration contains its own values and cannot inherit or cannot pass inheritance.

It is useful when you have a set of related values that reflect discrete alternatives such as days of the week, months, directions, status codes, etc.

Declaring enum Variable

The general syntax for declaring an enumeration is −

enum <enum_name> {
   enumeration list 
};

Explanation −

  • The enum_name specifies the enumeration type name.

  • The enumeration list is a comma-separated list of identifiers.

Each of the symbols in the enumeration list stands for an integer value, one greater than the symbol that precedes it. By default, the value of the first enumeration symbol is 0. For example −

enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };

Example of Enumeration (Enum)

The following is the basic example that demonstrates the use of an enum variable −

using System;
namespace EnumApplication {
   class EnumProgram {
      enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };

      static void Main(string[] args) {
         int WeekdayStart = (int)Days.Mon;
         int WeekdayEnd = (int)Days.Fri;
         
         Console.WriteLine("Monday: {0}", WeekdayStart);
         Console.WriteLine("Friday: {0}", WeekdayEnd);
         Console.ReadKey();
      }
   }
}

When the above code is compiled and executed, it produces the following result −

Monday: 1
Friday: 5

Specifying Enum Values

The first enum constant starts with 0, and the following constants increase sequentially. However, you can also specify custom values for enum constants while declaring them.

Example

In the following example, we are defining an enumeration with specific numeric values and demonstrating how to access both the name and numeric value of an enum member −

using System;
enum StatusCode
{
   Success = 200,
   NotFound = 404,
   ServerError = 500
}
class Program
{
   static void Main()
   {
      StatusCode status = StatusCode.NotFound;
      Console.WriteLine("Status: " + status);
      Console.WriteLine("Numeric Value: " + (int)status);
   }
}

Following is the output of the above code −

Status: NotFound
Numeric Value: 404

Enums with Switch Statements

Enums can be used in switch statements, you can use the enum constants instead of literal values in case statements.

Example

The following example demonstrates the use of enum with switch statements:

using System;

// Defining an enum for weekdays
enum Weekday {
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
}

class Program {
    static void Main() {
        // Setting a specific day
        Weekday today = Weekday.Wednesday;

        // Using enum in switch statement
        switch (today) {
            case Weekday.Sunday:
                Console.WriteLine("It's Sunday");
                break;
            case Weekday.Monday:
                Console.WriteLine("It's Monday.");
                break;
            case Weekday.Tuesday:
                Console.WriteLine("It's Tuesday.");
                break;
            case Weekday.Wednesday:
                Console.WriteLine("It's Wednesday.");
                break;
            case Weekday.Thursday:
                Console.WriteLine("It's Thursday.");
                break;
            case Weekday.Friday:
                Console.WriteLine("It's Friday.");
                break;
            case Weekday.Saturday:
                Console.WriteLine("It's Saturday.);
                break;
        }
    }
}

When the above code is compiled and executed, it produces the following result −

It's Wednesday.

Combining Multiple Values Using Enum Flags

By using the [Flags] attribute, you can combine multiple enum values using bitwise operators, which is useful for the programs where you need to handle permissions or settings.

Example

This example demonstrates how you can combine the multiple values using Enum flags:

using System;

[Flags]
// Defining an enum with bitwise flags for permissions
enum Permissions {
    None = 0,
    Read = 1,
    Write = 2,
    Execute = 4,
    FullControl = Read | Write | Execute
}

class Program {
    static void Main() {
        // Assigning
        Permissions userPermissions = Permissions.Read | Permissions.Write;

        // Displaying
        Console.WriteLine($"User's Permissions: {userPermissions}");

        // Checking
        Console.WriteLine($"You Have Write Permission? {userPermissions.HasFlag(Permissions.Write)}");
        Console.WriteLine($"You Have Execute Permission? {userPermissions.HasFlag(Permissions.Execute)}");
    }
}

When the above code is compiled and executed, it produces the following result −

User Permissions: Read, Write
You Have Write Permission? True
You Have Execute Permission? False

Parsing Enums from Strings or Integers

You can convert enums from both string and integer values. To convert from a string to an enum, use the Enum.Parse() method. To convert from an integer to a string, simply use the enum name.

Example

This example demonstrates how you can convert Enums from both string and integer values:

using System;

enum OrderStatus {
    Pending = 0,
    Processing = 1,
    Shipped = 2,
    Delivered = 3
}

class Program {
    static void Main() {
        // Convert String to Enum
        string input = "Processing";
        OrderStatus statusFromString = (OrderStatus)Enum.Parse(typeof(OrderStatus), input);
        Console.WriteLine($"Converted from string: {statusFromString}");

        // Convert Integer to Enum
        int value = 3;
        OrderStatus statusFromInt = (OrderStatus)value;
        Console.WriteLine($"Converted from integer: {statusFromInt}");
    }
}

When the above code is compiled and executed, it produces the following result −

Converted from string: Processing
Converted from integer: Delivered
Advertisements