home *** CD-ROM | disk | FTP | other *** search
/ PC Pro 2005 June (DVD) / DPPRO0605DVD.iso / dotNETSDK / SETUP.EXE / netfxsd1.cab / FL_Enums_cs________.3643236F_FC70_11D3_A536_0090278A1BB8 < prev    next >
Encoding:
Text File  |  2001-08-21  |  1.7 KB  |  57 lines

  1. using System;
  2.  
  3. enum Color {
  4.    Red,
  5.    Green,
  6.    Blue
  7. }
  8.  
  9.  
  10. class App {
  11.    static void PaintTheHouse(Color c) {
  12.       if (!Enum.IsDefined(typeof(Color), c))
  13.          throw(new ArgumentOutOfRangeException("color", c, c.ToString() + " is not a valid color value"));
  14.       Console.WriteLine("Painting the house " + c.ToString());
  15.    }
  16.  
  17.  
  18.    static void Main() {
  19.       // Create a variable of type Color and initialize it to Green
  20.       Color c = Color.Green;
  21.  
  22.       // Format() converts the number (1) to the symbol ("Green")
  23.       Console.WriteLine(c.ToString());      // Displays "Green"
  24.  
  25.       // ToString() converts the number (1) to the string ("1")
  26.       Console.WriteLine(c.ToString("D"));    // Displays 1
  27.  
  28.       // Returns array of Color enums
  29.       Color[] ca = (Color[]) Enum.GetValues(typeof(Color));
  30.       foreach (Color color in ca) {
  31.          Console.WriteLine("Value: {0}, Symbol: {1}", 
  32.             color.ToString("D"), color.ToString());
  33.       }
  34.  
  35.       // Since Blue is defined as 2, æcÆ is initialized to 2.
  36.       c = (Color) Enum.Parse(typeof(Color), "Blue");
  37.  
  38.       // Since Brown is not defined, an ArgumentException is raised
  39.       try {
  40.          c = (Color) Enum.Parse(typeof(Color), "Brown");
  41.       }
  42.       catch (ArgumentException) {
  43.          Console.WriteLine("Brown is not defined by the Color enumerated type.");
  44.       }
  45.  
  46.       PaintTheHouse((Color) 2);     // Blue
  47.       try {
  48.          PaintTheHouse((Color) 20);  // Not a defined color
  49.       }
  50.       catch (ArgumentOutOfRangeException) {
  51.          Console.WriteLine("Can't paint the house using a color with value 20.");
  52.       }
  53.  
  54.       Console.Write("Press Enter to close window...");
  55.       Console.Read();
  56.    }
  57. }