The C# compiler actually turns enumerations into regular class
types, and makes them behave like an enumeration by a combination of syntax sugar and some help from methods in the .NET framework (particularly the Type
and Enum
classes).
What actually happens when you declare an enum
type is that the compiler creates a hidden, specially-named class which conceptually looks like this:
public sealed class EnumName : Enum
{
public static readonly int FirstValue = 0;
public static readonly int SecondValue = 1;
// etc.
}
The Enum
base class is a special base class that you cannot use directly. It provides the ToString()
method. This sets off a series of function calls internal to the .NET framework. The code ends up in Type.GetEnumName()
and finally a private Type.GetEnumData()
method which uses reflection to examine the EnumName
class, look at its fields (enumeration values) and get and return their names.
The call graph (in chronological order) looks like this:
Enum.ToString()
Enum.InternalFormat(RuntimeType, object)
Enum.GetName(RuntimeType, object)
Type.GetEnumName(object)
Type.GetEnumRawConstantValues()
Type.GetEnumData(out string[], out Array)
Type.GetEnumNames()
Type.GetEnumData(out string[], out Array)
GetEnumData()
calls Type.GetFields()
and iterates over them, copying the name and integral value (enum value) of each field into the output array.