top button
Flag Notify
Site Registration

What is main use of Enumeration?

+2 votes
251 views
What is main use of Enumeration?
posted Jun 25, 2015 by Manikandan J

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
An enumeration type (also named an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable.

The main benefit of this is that constants can be referred to in a consistent, expressive and type safe way.

Take for example this very simple Employee class with a constructor:

You could do it like this:

public class Employee
{
    private string _sex;

    public Employee(string sex)
    {
       _sex = sex;
    }
}

But now you are relying upon users to enter just the right value for that string.

Using enums, you can instead have:

public enum Sex
{
    Male = 10,
    Female = 20
}

public class Employee
{
    private Sex _sex;

    public Employee(Sex sex)
    {
       _sex = sex;
    }
}    

This suddenly allows consumers of the Employee class to use it much more easily:

Employee employee = new Employee("Male");

Becomes:

Employee employee = new Employee(Sex.Male);

answer Jun 26, 2015 by Shivaranjini
...