This is the 15th day of my participation in the August More text Challenge. For details, see: August More Text Challenge

define

An enumeration is a set of named integer constants. Enumeration types are declared using the enum keyword.

C# enumerations are value types. In other words, an enumeration contains its own value and cannot inherit or pass inheritance.

Enumerations, like struct types, are programmer-defined types. A unique type consisting of a set of named constants called an enumerator list.

An enumeration type is defined as:

enumEnumeration name {variable1, the variable2. , variable n}/ / or
enumEnumeration name {variable1 = 1, the variable2 = 2. , variable n = n}Copy the code

It is customary here to leave the last variable without a comma to indicate the end of the enumeration.

Each enumeration type has an underlying integer type, which defaults to int. Each enumeration member is assigned a constant value of the underlying type; By default, the compiler assigns 0 to the first member and one more value to each subsequent member than the previous one.

If the value of an enumeration constant is specified, its subsequent enumeration constants increase by 1 from the current one.

As shown in the figure below, when the mouse is over WED, you can see that its value is 3:


Matters needing attention

  1. Like struct types, enumerations are value types and therefore store their data directly rather than storing data and references separately;

  2. Enumerations have only one type of members: named integer value constants;

  3. You cannot use modifiers on members of enumerated types. They all implicitly have the same accessibility as enumerations;

  4. Members of different enumeration types are not allowed to be compared, even if their structure and names are identical.

  5. Because members of an enumeration type are constants, they are accessible even when there are no variables of that enumeration type. Members of an enumeration type can be accessed by using the name of the enum type, the member reference operator and the member name.

  6. The base type specifies the storage size allocated for each enumerator. However, the conversion from enum to integer type needs to be done with explicit type conversion.

  7. In general, it is best to define an enumeration directly within a namespace so that all classes in that namespace can access it equally easily. However, you can also nest an enumeration within a class or structure.

Use the sample

enum WEEK
{
    MON = 1,
    TUE,
    WED,
    THU,
    FRI,
    SAT,
    SUN
}

class Program
{
    static void Main(string[] args)
    {
        // Convert to string
        string str = WEEK.MON.ToString();
        // Output: MON
        Console.WriteLine(str);

        // Convert to int
        int mon = (int)WEEK.MON;
        // Output: 1Console.WriteLine(mon); Console.ReadLine(); }}Copy the code