Why did Enums make constants instead of static values?

I understand that Enums are compiled as constants, so changing them leads to breaking changes. I wonder, why didn't Enums list the same as readonly static variables?

+5
source share
3 answers

They can be more efficient than fields, so there is no need to compile them in the same way when they can be directly embedded in IL.

[Enumerations] are loaded in the same one which loads the value of const. They are built directly into IL. Fields, on the other hand, require instructions for loading a field (ldsfld), which will slightly affect performance. Thus, enumerations are as fast as const with typical use; margins are slightly slower.

( Source )

+6
source

Both of these answers are technically correct, but skip the explanation of the differences between constants and statics (read-only). In C #, constants are always faster than readonly, and the reason is very simple and best expressed by a small code example:

const int MyConstant = 10;
static readonly int MyReadonly = 20;

static void Main()
{
    int result = MyConstant + MyReadonly;
    // the above statement will be resolved to:
    // int result = 10 + MyReadonly
}

. , . readonly, , , . :

static readonly Encoding = Encoding.GetEncoding("GB2132");

, , , GB2132. - . Static , readonly , . , .

, .

. . , :

enum MyEnum
{   
    First,
    Second,
    Third
}

static void Main()
{
    MyEnum test = MyEnum.First;

    if (test == MyEnum.Second)
    {
      // whatever
    }
}

:

const int MyEnum_First = 0;
const int MyEnum_Second = 1;
const int MyEnum_Third = 2;

static void Main()
{
    int test = MyEnum_First;

    if (test == MyEnum_Second )
    {
      // whatever
    }
}

, , , :

static void Main()
{
    int test = 0;

    if (test == 1 )
    {
      // whatever
    }
}
+8

From enum (C # link)

As with any constant, all references to individual values ​​of an enumeration are converted to numeric literals at compile time

Am I missing something?

+1
source

All Articles