What is main use of Enumeration?

后端 未结 10 1791
时光取名叫无心
时光取名叫无心 2020-12-08 07:35

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

10条回答
  •  南笙
    南笙 (楼主)
    2020-12-08 08:00

    Enumeration (Enum) is a variable type. We can find this variable type in C, C# and many other languages. Basic Idea for Enum is that if we have a group of variable of integer type (by default) then instead of using too much int values just use a Enum. It is efficient way. Let suppose you want to write rainbow colours then you may write like this:

    const int Red = 1;
    const int Orange = 2;
    const int Yellow = 3;
    const int Green = 4;
    const int Blue = 5;
    const int Indigo = 6;
    const int Violet = 7;
    

    here you can see that too many int declarations. If you or your program by mistake change the value of any integer varialbe i.e. Violet = 115 instead of 7 then it will very hard to debug.

    So, here comes Enum. You can define Enum for any group of variables type integers. For Enum you may write your code like this:

    enum rainBowColors
    {
     red=1,
     orange=2,
     yellow=3,
     green,
     blue=8,
     indigo=8,
     violet=16) 
    }; 
    

    rainBowColors is a type and only other variables of the same type can be assigned to this. In C#/C++ you need to type casting while in C you do not to type cast.

    Now, if you want to declare a variable of type rainBowColors then in C

    enum rainBowColors variableOne = red;
    

    And in C# / C++ you can do this as:

    rainBowColors variableOne = red;
    

提交回复
热议问题