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.

Advertisements

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: