Pages

Friday, April 24, 2009

Enum in C#

MSDN says:
An enumeration type (also named an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable.

You create a bit flags enum by applying the System.FlagsAttribute attribute and defining the values appropriately. That way you can use the bitwise operations like AND, OR and NOT on them.

In the following code example I've shown how to get Enum names and values, and how to use bitwise operations with enums.



    1 using System;
    2 
    3 namespace EnumTest
    4 {
    5   class Program
    6   {
    7     enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
    8 
    9     [Flags] // Enables bitwise operations
   10     public enum WaffleOptions
   11     {
   12       Cherries = 0x01,
   13       IceCream = 0x02,
   14       MapleSyrup = 0x04,
   15       WhippedCream = 0x08,
   16       Strawberries = 0x16
   17     }
   18 
   19 
   20     static void Main(string[] args)
   21     {
   22       int x = (int)Days.Monday;
   23       int y = (int)Days.Friday;
   24       Console.WriteLine("Monday = {0}", x);
   25       Console.WriteLine("Friday = {0}", y);
   26 
   27       // Output:
   28       // Monday = 0
   29       // Friday = 4
   30 
   31       WaffleOptions waffleFillings = WaffleOptions.Cherries | WaffleOptions.WhippedCream;
   32 
   33       Console.WriteLine("Waffle options are {0}", waffleFillings);
   34 
   35       // Output:
   36       // Waffle options are Cherries, WhippedCream
   37 
   38       // gets the string value of Days-enum at index 4, 
   39       // which is Friday (Monday=0, .. Sunday=6)
   40       string s = Enum.GetName(typeof(Days), 4);
   41       Console.WriteLine(s);
   42 
   43       // Output:
   44       // Friday
   45 
   46       // gets all the values of Days enum
   47       Console.WriteLine("The values of the Days Enum are: ");
   48       foreach (int i in Enum.GetValues(typeof(Days)))
   49         Console.Write("{0} ", i);
   50 
   51       // Output:
   52       // 0 1 2 3 4 5 6 7
   53 
   54       // gets all the names of Days enum
   55       Console.WriteLine("\nThe names of the Days Enum are:");
   56       foreach (string str in Enum.GetNames(typeof(Days)))
   57         Console.Write("{0} ", str);
   58 
   59       Console.ReadLine();
   60 
   61     }
   62   }
   63 }

When you have for example a string value that you want to parse or check if it is an enum, you need to use Parse method. Parse method convert strings to their corresponding enumeration values. However, that's not enough. If your value is for example 1234, Parse-method thinks it is a valid enum value, because it's an integer value. You need to check if that integer value is represented in the enum list, by using IsDefined method. Following example describes how to use those.

    1 using System;
    2 
    3 namespace EnumParseTest
    4 {
    5   class Tester
    6   {
    7     
    8     // here's some enums. As you can see, we don't have to assign integer value to enum (Yellow)
    9     enum Colors { Red = 1, Green = 2, Yellow };
   10 
   11     static void Main(string[] args)
   12     {
   13       Console.WriteLine();
   14 
   15       // here's string values that are later parsed & checked if they are in Colors-enum
   16       string[] colorStrings = { "Red", "Yellow", "Gray", "2", "12345"};
   17 
   18       foreach (string colorString in colorStrings)
   19       {
   20         try
   21         {
   22           Colors colorValue = (Colors)Enum.Parse(typeof(Colors), colorString);
   23           // We need to check if parsed value is a member of Colors enum
   24           // If we just parse the value, then value '12345' is assumed enum value.
   25           if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))
   26             Console.WriteLine("Converted string '{0}' to Enum value {1}.", colorString, colorValue.ToString());
   27           else
   28             Console.WriteLine("{0} is not a value of the Colors enumeration.", colorString);
   29         }
   30         catch (ArgumentException)
   31         {
   32           Console.WriteLine("'{0}' is not a member of the Colors enumeration.", colorString);
   33         }
   34       }
   35 
   36       /*
   37           Output:
   38           Converted string 'Red' to Enum value Red.
   39           Converted string 'Yellow' to Enum value Yellow.
   40           'Gray' is not a member of the Colors enumeration.
   41           Converted string '2' to Enum value Green.
   42           12345 is not a value of the Colors enumeration.              
   43        */
   44 
   45       Console.ReadLine();
   46     }
   47   }
   48 }

Enums in MSDN:

enum (C# Reference)

Enumeration Types (C# Programming Guide)

No comments:

Post a Comment