April 13, 2024

What is enum in C#?

This article describes basic overview of enums or how to create enum in C# or how to use enum in C#. Summery of the article:

  • What is Enumerations or enums?
  • Declaration of enums
  • Example of enum

What is Enumerations or enums?
Enumerations or enums is a set of named integer constants. In C# enums are User-Defined Value Types and enum constants must be integral numeric values. Its index starts from 0 and the value of each successive enumerator is increased by 1. For example consider the following enumeration. Here enumeration Sat is 0, Sun is 1, and Mon is 2

enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};

But we can use initializers to override the default value. Consider the following example.

enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

In this enumeration the sequence of elements is forced to start from 1 instead of 0. But it is recommended to set its value 0.

Declaration of enums
Enumerated type is declared using the enum keyword. The general syntax for declaring an enumeration is:

    enumeration list

The enumName specifies the enumeration type name.
The enumeration list is a comma-separated list of identifiers.

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

Example of enum
Example of enum in C#:

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

static void Main(string[] args)
    Console.WriteLine("Sunday: {0}", (int)Days.Sun);
    Console.WriteLine("Friday: {0}", (int)Days.Fri);

If we run the above code in a Console Application the output will be:

Sunday: 0
Friday: 5

That’s all about C# enum.

Rashedul Alam

I am a software engineer/architect, technology enthusiast, technology coach, blogger, travel photographer. I like to share my knowledge and technical stuff with others.

View all posts by Rashedul Alam →

2 thoughts on “What is enum in C#?

Leave a Reply

Your email address will not be published. Required fields are marked *