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
418 views
in Technique[技术] by (71.8m points)

c# - what is enum and where can we use it?

While I code every time I used List<T>, string, bool etc. I did't see anywhere a use of an enum. I have an idea that enum is a constant but in practice, where do we actually use it. If at all we can just use a

public const int x=10; 

Where do we actually use it?

Kindly help me

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

An enum is a convenient way to use names instead of numbers, in order to denote something. It makes your code far more readable and maintainable than using numbers. For instance, let that we say that 1 is red and 2 is green. What is more readable the following:

if(color == 1)
{
    Console.WriteLine("Red");
}
if(color == 2)
{
    Console.WriteLine("Green");
}

or this:

enum Color { Red, Green}

if(color == Color.Red)
{
    Console.WriteLine("Red");
}
if(color == Color.Green)
{
    Console.WriteLine("Green");
}

Furthermore, let that you make the above checks in twenty places in your code base and that you have to change the value of Red from 1 to 3 and of Green from 2 to 5 for some reason. If you had followed the first approach, then you would have to change 1 to 3 and 2 to 5 in twenty places ! While if you had followed the second approach the following would have been sufficient:

enum Color { Red = 3 , Green = 5 }

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

...