CHAPTER 4 CORE C# PROGRAMMING CONSTRUCTS, PART II
static void Main(string[] args)
{
Console.WriteLine("**** Fun with Enums *****");
EmpType emp = EmpType.Contractor;
...
}
// Prints out "Contractor = 100".
Console.WriteLine("{0} = {1}", emp.ToString(), (byte)emp);
Console.ReadLine();
Note The static Enum.Format() method provides a finer level of formatting options by specifying a desired
format flag. Consult the .NET Framework 4.5 SDK documentation for full details of the System.Enum.Format()
method.
System.Enum also defines another static method named GetValues(). This method returns an
instance of System.Array. Each item in the array corresponds to a member of the specified enumeration.
Consider the following method, which will print out each name/value pair within any enumeration you
pass in as a parameter:
// This method will print out the details of any enum.
static void EvaluateEnum(System.Enum e)
{
Console.WriteLine("=> Information about {0}", e.GetType().Name);
}
Console.WriteLine("Underlying storage type: {0}",
Enum.GetUnderlyingType(e.GetType()));
// Get all name/value pairs for incoming parameter.
Array enumData = Enum.GetValues(e.GetType());
Console.WriteLine("This enum has {0} members.", enumData.Length);
// Now show the string name and associated value, using the D format
// flag (see Chapter 3).
for(int i = 0; i < enumData.Length; i++)
{
Console.WriteLine("Name: {0}, Value: {0:D}",
enumData.GetValue(i));
}
Console.WriteLine();
To test this new method, update your Main() method to create variables of several enumeration
types declared in the System namespace (as well as an EmpType enumeration for good measure). The
following code is an example:
static void Main(string[] args)
{
Console.WriteLine("**** Fun with Enums *****");
...
144