05 Aug 2007
Enums in .NET are very powerful in defining options. By default when you define an enum it automatically assigns them sequential integer values from 1 (if you don't specify a start value). So how do we work with these dynamically? Well some say you can't, and they are wrong. But first let me cover the basics, if you want to skip over this scroll down to example 6.

Basics Of Enum

Example 1

In this example First would be equal to 1, Second to 2 and Third to 3.
public enum Demo { First, Second, Third }
Example 2

In this example First is equal to 1, Second to 222 and Third by 986.

public enum Demo { First = 1, Second = 222, Third = 986 } 
Example 3

What’s nice is that if you just want to change the start position then you can define that only, so in this example First is 10, Second is 11 and Third is 12.

public enum Demo { First = 10, Second, Third } 
Example 4

Even better is the ability to decorate the enum with the "flag" attribute, set the numbers (Raymond Chen explained why this is not done automatically) and use it as bitflags. Note the integer values are in traditional flag values with None set to 0 and All set to the combined value.

[Flags] 
public enum Demo 
{ 
None = 0, 
First = 1, 
Second = 2, 
Third = 4, 
All = 7 
} 
Example 5

So how do we use those flags? The code below will output:

First, Third

The code is:

static void Main(string[] args) 
{ 
    Demo Enum = Demo.First | Demo.Third; 
    Console.WriteLine(Enum); 
} 


Dynamically Using Flag with Enums

So here we are basics out of the way, and now on to the fun. I continue to use the definition in example 4 above.

Example 6

First I will show how to add a value to the enum variable. What I do is start off by defining the enum to none (0 value) then using the OR concat (|=) symbol I add each enum. This code will output:

Second, Third

The code is:

static void Main(string[] args) 
{ 
    Demo Enum = Demo.None; 
    Enum |= Demo.Second; 
    Enum |= Demo.Third; 
    Console.WriteLine(Enum); 
} 
Example 7

In this last example I will show how to remove an value from the enum variable. I start off by defining all (integer value of 7) and then I use the AND concat (&=) symbol and prefix the enum value with tilde (~). This code will output:

First, Third

The code is

static void Main(string[] args) 
{ 
    Demo Enum = Demo.All; 
    Enum &= ~Demo.Second; 
    Console.WriteLine(Enum); 
} 

Add new comment