Thursday, October 22, 2009

Controlling the Underlying Storage for an Enum

By default, the storage type used to hold the values of an enumeration is a System.Int32 (the C#
int); however, you are free to change this to your liking. C# enumerations can be defined in a similar
manner for any of the core system types (byte, short, int, or long). For example, if you want to
set the underlying storage value of EmpType to be a byte rather than an int, you can write the
following:

// This time, EmpType maps to an underlying byte.
enum EmpType : byte
{
Manager = 10,
Grunt = 1,
Contractor = 100,
VicePresident = 9
}
Changing the underlying type of an enumeration can be helpful if you are building a .NET
application that will be deployed to a low-memory device (such as a .NET-enabled cell phone or
PDA) and need to conserve memory wherever possible. Of course, if you do establish your enumeration
to use a byte as storage, each value must be within its range!
Declaring and Using Enums
Once you have established the range and storage type of your enumeration, you can use it in place
of so-called magic numbers. Because enumerations are nothing more than a user-defined type, you
are able to use them as function return values, method parameters, local variables, and so forth.
Assume you have a method named AskForBonus(), taking an EmpType variable as the sole parameter.
Based on the value of the incoming parameter, you will print out a fitting response to the pay bonus
request:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("**** Fun with Enums *****");
// Make a contractor type.
EmpType emp = EmpType.Contractor;
AskForBonus(emp);
Console.ReadLine();
}
// Enums as parameters.
static void AskForBonus(EmpType e)
{
switch (e)
{
case EmpType.Manager:
Console.WriteLine("How about stock options instead?");
break;
case EmpType.Grunt:
Console.WriteLine("You have got to be kidding...");
break;
case EmpType.Contractor:
Console.WriteLine("You already get enough cash...");
break;
case EmpType.VicePresident:
Console.WriteLine("VERY GOOD, Sir!");
break;
}
}
}

Notice that when you are assigning a value to an enum variable, you must scope the enum
name (EmpType) to the value (Grunt). Because enumerations are a fixed set of name/value pairs, it is
illegal to set an enum variable to a value that is not defined directly by the enumerated type:
static void Main(string[] args)
{
Console.WriteLine("**** Fun with Enums *****");
// Error! SalesManager is not in the EmpType enum!
EmpType emp = EmpType.SalesManager;
// Error! Forgot to scope Grunt value to EmpType enum!
emp= Grunt;
Console.ReadLine();
}

No comments:

Post a Comment