TOC

The community is working on translating this tutorial into Indonesian, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Advanced topics:

Enumerations

Enumerations are special sets of named values which all maps to a set of numbers, usually integers. They come in handy when you wish to be able to choose between a set of constant values, and with each possible value relating to a number, they can be used in a wide range of situations. As you will see in our example, enumerations are defined above classes, inside our namespace. This means we can use enumerations from all classes within the same namespace.

Here is an example of a simple enumeration to show what they are all about.

public enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }

All of these possible values correspond to a number. If we don't set them specifically, the first value is equal to 0, the next one to 1, and so on. The following piece of code will prove this, as well as show how we use one of the possible values from the enum:

using System;

namespace ConsoleApplication1
{
    public enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }

    class Program
    {
        static void Main(string[] args)
        {
            Days day = Days.Monday;
            Console.WriteLine((int)day);
            Console.ReadLine();
        }
    }
}

The output will be zero, because the Monday value maps directly to the number zero. Obviously we can change that - change the line to something like this:

public enum Days { Monday = 1, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }

If you run our code again, you will see that the Monday now equals 1 instead of 0. All of the other values will be one number higher as well as a result. You can assign other numbers to the other values as well. Because of the direct mapping to a number, you can use numbers to get a corresponding value from the enumeration as well, like this:

Days day = (Days)5;
Console.WriteLine(day);
Console.ReadLine();

Another cool feature of enumerations is the fact that you can attach a string representation of the values as well. Change the above example to something like this:

static void Main(string[] args)
{
    string[] values = Enum.GetNames(typeof(Days));
    foreach(string s in values)
        Console.WriteLine(s);
    
    Console.ReadLine();
}

The Enum class contains a bunch of useful methods for working with enumerations.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!