Besides the structures, C# supports another value type Enumeration. In this article, we are going to talk more about Enumerations in C#.

If you want to see complete navigation of this tutorial, you can do that here C# Intermediate Tutorial.

To download the source code, you can visit Enumerations in C# Source Code. 

We are going to split this article into the following sections:

Working with Enumerations in C#

Suppose we need to represent days in a week in our C# project. We can use an integer number to represent every single day in a week (from 0 to 6), and even though that would work just fine it is not readable at all. This is where enumerations excel.

To declare enumeration we can use the following syntax:

After we have declared our enumeration, we can use it in exactly the same way as any other type:

As we can see, we must write DaysInWeek.Monday and not just Monday because all enumeration literal names are in scope of their enumeration type.

Choosing Enumeration Literal Values

Internally, an enumeration type assigns the integer value to every element inside that enumeration. Those numbers start at 0 and increase by 1 for every other element. In our previous example, we print out the value that matches with the exact element of an enumeration. But we can print the integer value as well by casting it into its underlying type:

If we prefer, we can assign a specific integer constant to the enumeration elements:

If we do it like this, Monday will have the value 1 and all the others will be increased by one (Tuesday=2, Wednesday=3…). But we can assign a random value to each of the elements:

Of course, it is always a better way to assign integer values with the equal progression (1, 2, 3… or 10, 20, 30…).

Choosing an Enumerations Underlying Type

When we declare an enumeration, the compiler assigns integer values to all of the elements. But we can change that. We can provide a different type right after the name of an enumeration:

By doing this, we save our memory because the int type is taking more memory than the short, and we don’t need for our example, greater capacity of the short data type.

Conclusion

In this article, we have learned:

  • What is enumeration and how to create one
  • How to work with literal values in enumerations

In the next article, we are going to talk about Enumerations in C#.

If you have enjoyed reading this article and if you would like to receive the notifications about the freshly published .NET Core content we encourage you to subscribe to our blog.