Free mag vol1 | Page 208

CHAPTER 4  CORE C# PROGRAMMING CONSTRUCTS, PART II 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("Em pType uses a {0} for storage", Enum.GetUnderlyingType(emp.GetType())); Console.ReadLine(); If you were to consult the Visual Studio 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 15, 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))); Dynamically Discovering an enum’s Name/Value Pairs Beyond the Enum.GetUnderlyingType() method, all C# enumerations support a method named ToString(), which returns the string name of the current enumeration’s value. The following code is an example: static void Main(string[] args) { Console.WriteLine("**** Fun with Enums *****"); EmpType emp = EmpType.Contractor; AskForBonus(emp); // Prints out "emp is a Contractor". Console.WriteLine("emp is a {0}.", emp.ToString()); Console.ReadLine(); } If you are interested in discovering the value of a given enumeration variable, rather than its name, you can simply cast the enum variable against the underlying storage type. The following is an example: 143