Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is enum and where can we use it?

Tags:

c#

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

like image 996
saireddy Avatar asked Dec 14 '22 04:12

saireddy


1 Answers

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 }
like image 54
Christos Avatar answered Jan 01 '23 04:01

Christos