SoFunction
Updated on 2025-03-06

Deep understanding of enums in C#

An enum type is a value type that is used to declare a set of named constants.

(1) Enumeration declaration: Enumeration declaration is used to declare a new enumeration type.
Access rhetorical symbol enum enum name: basic type

Copy the codeThe code is as follows:

    {
Enumerate members
    }

The underlying type must be able to represent all enum values ​​defined in the enum. Enumeration declarations can explicitly declare the byte, sbyte, short, ushort, int, uint, long, or ulong types as the corresponding base types. An enumeration declaration that does not explicitly declare the base type means that the corresponding base type is int.

(2) Enumerate members
An enum member is a named constant for the enum type. Any two enum members cannot have the same name. Each enum member has an associated constant value. The type of this value is the basic type of the enum. The constant value of each enum member must be within the range of the underlying type of the enum.

Example:

Copy the codeThe code is as follows:

        public enum TimeofDay:uint
        {
            Morning=-3,
            Afternoon=-2,
            Evening=-1
         }  

A compile-time error occurs because the constant values ​​-1, -2 and -3 are not within the scope of the base integer uint.

(3) Enumerate member default values        
The first enum member declared in the enum type has a default value of zero.
The subsequent enum member value is obtained by adding 1 to the previous enum member (in text order). The added value must be within the range of the values ​​that the underlying type can represent (value range); otherwise, a compile-time error will occur.

Example:

Copy the codeThe code is as follows:

        public enum TimeofDay:uint
        {
            Morning,
            Afternoon,
            Evening
         }  

Morning's value is 0, Afternoon's value is 1, and Evening's value is 2.

(4) Display assignment for enumeration members
Allows multiple enum members to have the same value.
The value of the enum member that has no assignment is displayed, and the value of the previous enum member is always +1.
Example

Copy the codeThe code is as follows:

        public enum Number
        {
            a=1,
            b,
            c=1,
            d
        }

The value of b is 2 and the value of d is 2.
Note: None of the above enum values ​​can exceed its base type range. Otherwise, an error will be reported.

(5) Conversion of enumeration type and basic type
The basic type cannot be implicitly converted to an enum type
Enum types cannot be implicitly converted to base types either

Example:

Copy the codeThe code is as follows:

    public enum Number
    {
        a,
        b,
        c,
        d
    }

    class Test
    {
        public static void Main()
        {
int i=;//Error, type conversion (int)
            Number n;
n=2

//like:

((int));//output:0

((Number)1); //output:b
        }
    }


(6) Type
A type is an abstract base class for all enum types, and members inherited from it are available in any enum type.
It is not an enum type itself. Instead, it is a class type from which all enum types are derived.

(7) Use enumeration type

Copy the codeThe code is as follows:

        using System;
        public enum TimeofDay
        {
             Morning,
             Afternoon,
             Evening
        }   
        class Test
        {
             static void WriteGreeting(TimeofDay timeofDay)
             {           
                  switch(timeofDay)
                  {
                       case :
                            ("good morning");
                            break;
                       case :
                            ("good afternoon");
                            break;
                       case :
                            ("good evening");
                            break;
                  }
             }
             static void Main()
             {
                  WriteGreeting();
                  WriteGreeting();
                  WriteGreeting();
             }
        }

Declarations of C# enumerations can appear in the same place as class declarations (that is, generated in the namespace).

The declaration of C# enumeration includes names, access permissions, inherent types, and members of the enum.

C# enumeration learning needs to be paid attention to:

A type is an abstract base class for all enum types (it is a unique type that is different from the base type of an enum type), and members inherited from are available in any enum type. There is a boxing conversion from any enum type to , and there is an unboxing conversion from to any enum type. It is not an enum type itself. Instead, it is a class type from which all enum types are derived. Types are derived from type, which in turn derives from type object. At runtime, the value of the type can be null or a reference to the boxed value of any enumeration type.

Advantages of C# enumeration:

◆Enums can make the code easier to maintain and help ensure that the variables are assigned legal, expected values.

◆Enums make the code clearer, allowing for descriptive names to represent integer values ​​rather than numbers with fuzzy meanings.

◆Enums make code easier to type. When assigning values ​​to instances of enum types, the IDE will pop up a list box with acceptable values ​​through IntelliSense, which reduces the number of key presses and allows us to recall possible values

Traversal enumeration:

Copy the codeThe code is as follows:

protected void Page_Load(object sender, EventArgs e)
    {
        int i = 1;
        foreach (string s in (typeof(Days)))
        {
            (new ListItem((typeof(Days), s).ToString(), ()));
            i++;
            (s + "---" + (typeof(Days), s).ToString() + "<br/>");
        }

        String[] str = (typeof(Days));
        for (int j = 0; j < ; j++)
        {
            (str[j] + "<br/>");
            (new ListItem(str[j], (j + 1).ToString()));
        }
    }

    enum Days { saturday = 1, Sunday, Mondy, Tuesday, Wednesday, Thursday, Friday };
    enum color { red = 1, green = 2, blue = 4, yellow = 8 };


Convert:
Copy the codeThe code is as follows:

protected void Page_Load(object sender, EventArgs e)
    {
//Convert:
        color mc =(color) (typeof(color),"red");
        (mc+"<br/>");//output:red
        String str = (typeof(color), "2").ToString();
        (str+"<br/>");//output:red
        if ((typeof(Days),"Monday"))
        {
            Days ds = (Days)(typeof(Days),"Monday");
            (ds+"<br/>");
             ds = (Days)(typeof(Days), "3");
            (ds + "<br/>");
        }
    }

    enum Days { saturday = 1, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday };
    enum color { red = 1, green = 2, blue = 4, yellow = 8 };


//Retrieve an array of constant values ​​in the specified enum:
Copy the codeThe code is as follows:

protected void Page_Load(object sender, EventArgs e)
    {
//Retrieve the array of constant values ​​in the specified enum:
        foreach (int  item in (typeof(Days)))
        {
            ("<br>"+item);
        }

        foreach (int item in (typeof(color)))
        {
            ("<br>"+item);
        }
    }

    enum Days { saturday = 1, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday };
    enum color { red = 1, green = 2, blue = 4, yellow = 8 };


Common methods of C# enumeration <1> Get enumeration string

TimeOfDay time = ; 
(());//Output: Afternoon C# Enumeration Common Methods <2>() Method

This method takes 3 parameters, the first parameter is the enumeration type to be used. The syntax is the enumeration class name followed by the keyword typeof and placed in brackets. The typeof operator will be discussed in detail in Chapter 5. The second parameter is the string to be converted, and the third parameter is a bool, specifying whether to ignore case when performing conversion. Finally, note that the() method actually returns an object reference - we need to explicitly convert this string to the required enum type (this is an example of an unboxing operation). For the above code, 1 will be returned as an object, corresponding to the enum value. When explicitly converted to int, 1 is generated again.

TimeOfDay time2 = (TimeOfDay)  
(typeof(TimeOfDay), "afternoon", true); 
((int)time2);//Output 1

Common methods of enumeration <3> to get the name corresponding to a certain value of the enumeration

= (typeof(TimeOfDay), 0); 
= ((TimeOfDay)0).ToString();//Return: Morning

Both methods can be implemented, but when their values ​​go beyond the bounds (not the values ​​listed in the enumeration), there is a certain difference. You can choose the right method according to your needs.

= ((TimeOfDay)5).ToString();  
//Return: 5, if the boundary is exceeded, return to the original value
= (typeof(TimeOfDay), 5);  
//Return: empty string, if cross-boundary, return empty string

Common methods of C# enumeration <4> to obtain all values ​​of the enum

foreach (int i in (typeof(TimeOfDay))) 
+= ();

C# Enumeration Common Methods <5>Enum all names

foreach(string temp in (typeof(TimeOfDay))) 
+=temp;