Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is main use of Enumeration?

Tags:

c#

enums

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# ?

like image 230
Red Swan Avatar asked Aug 19 '10 06:08

Red Swan


People also ask

Why do we use enumeration in C?

Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.

How do you explain enumeration?

An enumeration is a complete, ordered listing of all the items in a collection. The term is commonly used in mathematics and computer science to refer to a listing of all of the elements of a set.

What is the best example of enumeration?

Enumeration means counting or reciting numbers or a numbered list. A waiter's lengthy enumeration of all the available salad dressings might seem a little hostile if he begins with a deep sigh. When you're reciting a list of things, it's enumeration.


2 Answers

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); 
like image 124
David Hall Avatar answered Oct 12 '22 18:10

David Hall


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.

like image 20
spencer nelson Avatar answered Oct 12 '22 17:10

spencer nelson