What Lies Beneath Enum types

Enum types are used extensively within .NET framework to represent a group of named constant integers (default underlying type of enum elements is int) that you can use as method arguments, return values, etc; to make your program more readable and maintainable.

Once your codes are compiled into IL, all enum(s) that you use in your codes will be substituted with the underlying value. Therefore, knowing the actual values of enum elements is useful in some scenarios such as when reading the IL of a disassembled assembly.

This can be achieved easily using the reflection facility provided by .NET framework. Let say you want to see what’s inside the System.Data.DataRowState enum type, you can write and execute the following codes to list all the enum elements and the underlying integer value that each element represents:
Type dt = typeof (DataRowState);
foreach (string s in Enum.GetNames(dt))
{
    Console.WriteLine("{0} = {1}", s, Convert.ToInt32(
        Enum.Parse(dt, s)));

These codes will basically print the names of all members for the enum type in question, and the underlying integer values next to the names.

Posted on January 11, 2008, in Code Junky. Bookmark the permalink. Leave a comment.

Leave a comment