Enumerations in C#

Enumeration is a special set of named attributes, which are usually integers in the set of all map numbers, when you want to be able to choose between a group of constant values, and with each potential value related to any number, Can be used in a wide range of. As you will see in our example, enumeration is defined above the sections within our namespace. This means that we can use enumeration from all classes within the same namespace.

public enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } 
All of these potential values correspond to a number if we do not specifically set them, then the first value is equal to 0, the next 1 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 your code again, you will see that Monday is now equal to 1 compared to 0. All other values will have a number as well as results. You can assign other numbers along with other values. Due to the direct mapping of a number, you can also use numbers to get values related to calculations, such as:
Days day = (Days)5;
Console.WriteLine(day);
Console.ReadLine();
Another cool feature of enumerations is the fact that you can 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();
}
Share on Google Plus

About It E Research

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment