Thursday, October 22, 2009

The System.Enum Type

The interesting thing about .NET enumerations is that they gain functionality from the System.Enum
class type. This class defines a number of methods that allow you to interrogate and transform a
given enumeration. One helpful method is the static Enum.GetUnderlyingType(), which as the name
implies returns the data type used to store the values of the enumerated type (System.Byte in the
case of the current EmpType declaration).
static void Main(string[] args)
{
Console.WriteLine("**** Fun with Enums *****");
// Make a contractor type.
EmpType emp = EmpType.Contractor;
AskForBonus(emp);
// Print storage for the enum.
Console.WriteLine("EmpType uses a {0} for storage",
Enum.GetUnderlyingType(emp.GetType()));
Console.ReadLine();
}
If you were to consult the Visual Studio 2008 object browser, you would be able to verify that
the Enum.GetUnderlyingType() method requires you to pass in a System.Type as the first parameter.
As fully examined in Chapter 16, Type represents the metadata description of a given .NET entity.
One possible way to obtain metadata (as shown previously) is to use the GetType() method,
which is common to all types in the .NET base class libraries. Another approach is to make use of
the C# typeof operator. One benefit of doing so is that you do not need to have a variable of the
entity you wish to obtain a metadata description of:
// This time use typeof to extract a Type.
Console.WriteLine("EmpType uses a {0} for storage",
Enum.GetUnderlyingType(typeof(EmpType)));

No comments:

Post a Comment