26

What is main use of Enumeration in c#?

Edited:- suppose I want to compare the string variable with the any enumeration item then how i can do this in c# ?

Red Swan
  • 15,157
  • 43
  • 156
  • 238

10 Answers10

51

The definition in MSDN is a good place to start.

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);
David Hall
  • 32,624
  • 10
  • 90
  • 127
  • 2
    +1 for the answer but i think it should be new Employee – Mina Gabriel Dec 21 '13 at 02:48
  • 8
    @MinaGabriel ha thanks! Around three years ago but still a bit embarrassing. – David Hall Dec 21 '13 at 03:22
  • I learnt about Enum recently. Was wondering what I could do with it. This is one of a practical example. – Unnikrishnan Nov 08 '15 at 14:49
  • 2
    I still cannot understand why int values are assigned to data inside the enum – vigamage Feb 19 '16 at 06:03
  • 2
    @vigamage by default an enumeration will assign integer values to whatever's in the enum list, starting at 0. you can override this by asserting that an element is a specific integer value. you can see this by doing (int)Sex.Male or (int)Sex.Female. – DForck42 Sep 19 '16 at 15:08
  • So the idea is to make the use of the Employee constructor safer? Instead of using a string we'll be using an `enum` type, which is this case is assigning and `int` of 10 to it. – carloswm85 Jun 23 '22 at 22:57
26

Often you find you have something - data, a classification, whatever - which is best expressed as one of several discrete states which can be represented with integers. The classic example is months of the year. We would like the months of the year to be representable as both strings ("August 19, 2010") and as numbers ("8/19/2010"). Enum provides a concise way to assign names to a bunch of integers, so we can use simple loops through integers to move through months.

spencer nelson
  • 4,365
  • 3
  • 24
  • 22
11

Enums are strongly typed constants. 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.

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();
        }
    }
}
e4rthdog
  • 5,103
  • 4
  • 40
  • 89
Mukesh Kumar
  • 2,354
  • 4
  • 26
  • 37
6

Enumeration (Enum) is a variable type. We can find this variable type in C, C# and many other languages. Basic Idea for Enum is that if we have a group of variable of integer type (by default) then instead of using too much int values just use a Enum. It is efficient way. Let suppose you want to write rainbow colours then you may write like this:

const int Red = 1;
const int Orange = 2;
const int Yellow = 3;
const int Green = 4;
const int Blue = 5;
const int Indigo = 6;
const int Violet = 7;

here you can see that too many int declarations. If you or your program by mistake change the value of any integer varialbe i.e. Violet = 115 instead of 7 then it will very hard to debug.

So, here comes Enum. You can define Enum for any group of variables type integers. For Enum you may write your code like this:

enum rainBowColors
{
 red=1,
 orange=2,
 yellow=3,
 green,
 blue=8,
 indigo=8,
 violet=16) 
}; 

rainBowColors is a type and only other variables of the same type can be assigned to this. In C#/C++ you need to type casting while in C you do not to type cast.

Now, if you want to declare a variable of type rainBowColors then in C

enum rainBowColors variableOne = red;

And in C# / C++ you can do this as:

rainBowColors variableOne = red;
Mukesh Kumar
  • 2,354
  • 4
  • 26
  • 37
Ali Shan
  • 334
  • 3
  • 11
4

Another advantage of using Enum is that in case of any of the integer value needs to be changed, we need to change only Enum definition and we can avoid changing code all over the place.

Prinshul Jain
  • 116
  • 1
  • 6
4

There are two meanings of enumeration in C#.

An enumeration (noun) is a set of named values. Example:

public enum Result {
  True,
  False,
  FileNotFound
}

Enumeration (noun form of the verb enumerate) is when you step through the items in a collection.

The IEnumerable<T> interface is used by classes that provide the ability to be enumerated. An array is a simple example of such a class. Another example is how LINQ uses it to return results as enumerable collections.

Edit:

If you want to compare a string to an enum value, you either have to parse the string to the enum type:

if ((Result)Enum.Parse(typeof(Result), theString) == Result.True) ...

or convert the enum value to a string:

if (theString == Result.True.ToString()) ...

(Be careful how you compare the values, depending on whether you want a case sensetive match or not.)

If you want to enumerate a collection and look for a string, you can use the foreach command:

foreach (string s in theCollection) {
  if (s == theString) {
    // found
  }
}
Community
  • 1
  • 1
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • if ((Result)Enum.Parse(Result, theString) == Result.True) Correction if ((Result)Enum.Parse(typeof(Result), theString) == Result.True) as per my knowledge – Red Swan Aug 19 '10 at 07:34
  • Anyways, which will be best perform wise ? first method (parsing method) of comparison. or second method – Red Swan Aug 19 '10 at 07:43
  • @Lalit: Thanks, I made the correction. I think that the performance will be pretty much the same. It's probably somewhat faster to turn an enum into a string, but on the other hand it's slower to compare strings than enum values. – Guffa Aug 19 '10 at 08:26
3

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.

http://msdn.microsoft.com/en-us/library/cc138362.aspx

anishMarokey
  • 11,279
  • 2
  • 34
  • 47
2

Enumeration (ENUM)

An enum is a value type with a set of related named constants often referred to as an enumerator list. The enum keyword is used to declare an enumeration. It is a primitive data type, which is user defined.

Enums type can be integer (float, int, byte, double etc.). But if you used beside int it has to be cast.

enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
enum Months : byte { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec }; 
Deepak
  • 121
  • 5
0

Lets Take an Example we are taking normal constant in a class like int a=10;

by mistakely we assign new value to that variable in that same class like a=20; then we will get wrong data when we want access them. enum provide secure way of accessing constant.

Also if we have many feild constant in a class we had to memorize them if we want to use them in a class. but enum contains group of related name constant, if we want to access the constant then only we had to memorize enum name.

0

Enumerations in my experience have worked in very specific cases and should be used when you absolutely need to maintain this in your application. Problems come into play with Enums when you are working with multiple developers and some new developer comes on to a project and can adds a enum to the application no errors everything builds but then you have another full stack developer that maintains this same list in a lookup table in a different order. Kaboom!!!!

Burned way to many times with that one even if not intentional. Rule of thumb don't maintain a list of enums in a app over 5 or 6 items. If higher you might as well store them in a lookup table in the DB of your choice.

sleath
  • 871
  • 1
  • 13
  • 42