Free mag vol1 | Page 207

CHAPTER 4  CORE C# PROGRAMMING CONSTRUCTS, PART II Declaring enum Variables Once you have established the range and storage type of your enumeration, you can use it in place of socalled “magic numbers.” Because enumerations are nothing more than a user-defined data 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 ThisMethodWillNotCompile() { // Error! SalesManager is not in the EmpType enum! EmpType emp = EmpType.SalesManager; // Error! Forgot to scope Grunt value to EmpType enum! emp = Grunt; } 142