Best Industrial Training in C,C++,PHP,Dot Net,Java in Jalandhar

Wednesday, 26 December 2012

Enumerations

Enumerations

Enumerated type (also called enumeration or enum) is a data type consisting of a set of named values. A variable that has been declared as having an enumerated type can be assigned any of the enumerators as a value. Enumerations make the code more readable.
using System;

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

    static void Main()
    {

        Days day = Days.Monday;
        
        if (day == Days.Monday)
        {
            Console.WriteLine("It is Monday");
        }

        Console.WriteLine(day);

        foreach(int i in Enum.GetValues(typeof(Days)))
            Console.WriteLine(i);
    }
}
In our code example, we create an enumeration for week days.
enum Days 
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}
The enumeration is created with a enum keyword. The Monday, Tuesday ... barewords store in fact numbers 0..6.
Days day = Days.Monday;
We have a variable called day, which is of enumerated type Days. It is initialized to Monday.
if (day == Days.Monday)
{
    Console.WriteLine("It is Monday");
}
This code is more readable than if comparing a day variable to some number.
Console.WriteLine(day);
This line prints Monday to the console.
foreach(int i in Enum.GetValues(typeof(Days)))
    Console.WriteLine(i);
This loop prints 0..6 to the console. We get underlying types of the enum values. For a computer, an enum is just a number. The typeof is an operator used to obtain the System.Type object for a type. It is needed by the GetValues() method. This method returns an array of the values of in a specified enumeration. And the foreach keyword goes through the array, element by element and prints them to the terminal.

We further work with enumerations.
using System;

class CSharpApp
{
    public enum Seasons : byte
    {
        Spring = 1,
        Summer = 2,
        Autumn = 3,
        Winter = 4
    }

    static void Main()
    {
        Seasons s1 = Seasons.Spring;
        Seasons s2 = Seasons.Autumn;
        
        Console.WriteLine(s1);
        Console.WriteLine(s2);
    }
}
Seasons can be easily used as enums. We can specify the underlying type for the enum plus we can give exact values for them.
public enum Seasons : byte
{
    Spring = 1,
    Summer = 2,
    Autumn = 3,
    Winter = 4
}
With a colon and a data type we specify the underlying type for the enum. We also give each member a specific number.
Console.WriteLine(s1);
Console.WriteLine(s2);
These two lines print the enum values to the console.
$ ./seasons.exe 
Spring
Autumn
Output.

No comments:

Post a Comment