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# ?
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.
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.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With