Type of listing in C #

When we create an enumeration type variable and assign an enumeration value to it

enum Members{HighlyQualified, Qualified, Ordinary} class { static void Main() { Members developers = Members.HighlyQualified; Console.WriteLine(developers);//write out HighlyQualified } } 

Since enum is a value type, therefore, the value of the developers is stored on the stack that is returned by Member.HighlyQualified.Here we clearly know that the value of the developers is a string that refers to the location of the character memory.

Now

1. If we have included members. HighlyQualifed for int, then the return value is 0. How does this happen?

2. What value is actually stored on the stack for the enumeration type?

+5
source share
2 answers

It’s clear here that the meaning of developers is a string that refers to the location of the character memory.

No no. The value of developers is of type Members . It is converted to a string using the Console.WriteLine method. You will call the Console.WriteLine(object) overload, which will place the value - and then Console.WriteLine will call ToString on that value in the box, specifying the corresponding name of the enumeration value.

If we transfer members. HighlyQualifed for int, then the return value is 0. How does this happen?

HighlyQualified is the first member declared in Members , and you have not specified any specific value. By default, the C # compiler assigns the value 0 to the first declared value, and then increments by 1 each time. If you drop Members.Qualified to int , you will get 1.

What value is actually stored on the stack for the enum type?

A value that is actually just a number. (In this case, int , because it is the base type by default. But the stack slot has the correct type - the enumeration type.

+10
source

The documentation explains the basic type:

By default, the base type of each element in the enumeration is int.

and how the values ​​are generated if they are not explicitly specified:

If you do not specify values ​​for the items in the list of enumerators, the values ​​will be automatically increased by 1.

So in your case the declaration is equivalent to:

 enum Members : int { HighlyQualified = 0, Qualified = 1, Ordinary = 2 } 

That on the stack is the type enum ( Members in this case), and when you call Console.WriteLine , it calls ToString on this, for which for the documents for this , it returns:

string containing the name of the constant

+3
source

All Articles