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
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 }
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