Enumerations under the Hood

Summary:
Enumerations are implemented as value types that derive from System.Enum and define a constant per each name / value pair.

  • An enumeration is a value type
  • It derives from System.Enum which derives from System.ValueType
  • May contain no members other than its names and values
  • Emitted as a structure that holds the value and defines constant per each name

Let's look under the hood of enumerations and learn how they are implemented.

First of all, an enumeration is always a value type. This shouldn't come as a surprise since an enum simply encapsulates one numeric value. Due to its small size and simplicity, as well as the fact that inheritance doesn't play a role with enums, a value type is the natural choice.

An enumeration always derives from System.Enum, which in turn derives from System.ValueType. System.Enum offers some useful methods which we will cover in the next section.

The body of an enum cannot contain any members other than the name and value pairs. It must not contain any methods, properties and so on. Actually some programmers find that enum methods could be useful if existed. While it's not possible to define method within an enum, it is possible to simulate them using extension methods which are discussed in module 6.

When we define an enum the compiler emits something that looks like the following C# pseudo code.

Here we have the definition of Department as a structure that derives from System.Enum.

01struct Department : System.Enum
02{
03    public int value__;
04
05    public const Department Sales = (Department)0;
06    public const Department IT = (Department)1;
07    public const Department RnD = (Department)2;
08    public const Department Management = (Department)3;
09}

The only instance field it has is value__ which contains the actual numeric value of the current enum instance. There is also a definition of constants, one per each key value pair. Here we can see for example that the name Sale has a value of 0. Keep in mind that this is just pseudo code. It won't actually compile, mainly because it's illegal to specify a base class for a structure.

Since enum defines its name / value pairs as constants, it shares one shortcoming of constants when it comes to versioning. We'll discuss this in module 6 when we take a closer look at constants.