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
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
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.
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);
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.
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
}
}