Search code examples
c#memory-managementenumsreferencevalue-type

Enumeration type in c#


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

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

Since enum is value type so the value of developers is stored on stack which is returned by Members.HighlyQualified.Here we are clear that the value of developers is string which reference to the memory location of characters.

Now,

1.If we cast Members.HighlyQualifed to an int then the value returned is 0. How it happens?

2.What value is really stored on stack for an enumeration type ?


Solution

  • Here we are clear that the value of developers is string which reference to the memory location of characters.

    No, it's not. The value of developers is of type Members. It's converted to a string by the Console.WriteLine method. You'll be calling the Console.WriteLine(object) overload, which boxes the value - and then Console.WriteLine will call ToString on that boxed value, giving the appropriate enum value name.

    If we cast Members.HighlyQualifed to an int then the value returned is 0. How it happens?

    HighlyQualified is the first member declared in Members, and you haven't assigned any specific value. By default, the C# compiler assigns a value of 0 to the first declared value, then increments by 1 each time. If you cast Members.Qualified to int, you'd get 1.

    What value is really stored on stack for an enumeration type ?

    The value, which is effectively just a number. (In this case, an int because that's the default underlying type. But the stack slot has the right type - the enum type.