Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

c# - What is main use of Enumeration?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...