ENUMERATIONS IN C#

C sharpThe enumerations in C Sharp are also types introduced by us such as classes and structs and like the latter they are value types. Enums are data structures that the language makes available to us to improve the readability and security of our programs. They allow us to choose from a series of well-predefined values. Suppose our code handles the days of the week, let’s see how this enum is declared.

using System;

namespace Enumerazioni
{
    enum GiorniSettimana{Lunedi,martedi,mercoledi,giovedi,venerdi,sabato,domenica};
    class Program
    {
        static void Main(string[] args)
        {
             
        }
    }
}

As you can see, the enum keyword is used followed by a valid identifier and an enumeration of values enclosed in curly brackets. To assign our enumeration to a variable we declare the type, the variable and to the right of the assignment operator a value among those allowed. The syntax is shown below.

ENUMERATIONS IN C SHARP THE VALUES OF AN ENUMERATION

When an enum is created, the compiler behind the scenes by default generates an int and assigns the enumeration entries to integers in ascending order. We can access these compiler-generated integers with a simple cast, but there must be a more than valid reason why the enum would be useless.

By default the compiler generates an int, nothing prevents us from changing it with a byte.

using System;

namespace Enumerazioni
{
    enum GiorniSettimana:byte{Lunedi,martedi,mercoledi,giovedi,venerdi,sabato,domenica};
    class Program
    {
        static void Main(string[] args)
        {
            
        }
    }
}

We can also modify the values underlying our enumeration that is:

using System;

namespace Enumerazioni
{
    enum GiorniSettimana:byte{Lunedi=10,martedi=20,mercoledi=30,giovedi,venerdi,sabato,domenica};
    class Program
    {
        static void Main(string[] args)
        {
             
        }
    }
}

the remaining values will be assigned progressively by one unit from 31 to 34.

using System;
namespace Enumerazioni
{
    enum GiorniSettimana:byte{Lunedi=10,martedi=20,mercoledi=30,giovedi,venerdi,sabato,domenica};
    class Program
    {
        static void Main(string[] args)
        {
           GiorniSettimana gs = GiorniSettimana.domenica;
           if(gs==GiorniSettimana.domenica)
              Console.WriteLine("Domenica");
           int giorno = (int)GiorniSettimana.domenica;
           /*--WE CAN ACCESS THE WHOLE WHICH IS BEHIND THE ENUMERATION WITH A SIMPLE CAST*/
           Console.WriteLine(giorno);   
        }
    }
}

LINK TO PREVIOUS POST

LINK TO THE CODE ON GITHUB