Using the Flags attribute
The other day I had to implement a method that works the same way as the Regex ctor (allow multiple options to be set). Basically, I needed to have an enumeration that used the Flags attribute. Since I had never done this before, it was rather interesting. The 1.0 Framework help docs are pretty sparse (which is what I had to use) on this topic, so I thought I would write about my implementation here.
I have a method I was exposing called:
public void ExecuteColor( ColorOptions options ){
//in here I had to check to see which color was selected.
//I also wanted to provide the method caller with the option of specifying many colors, or no colors,
// but did not want to use the params keyword.
}
Creating the Enum
This can be accomplished by creating an enum with the Flags attribute.
It looks like:
[Flags]
public enum ColorOptions
{
None =0,
Red = 1,
Blue = 2,
White = 4,
Black = 8,
Green = 16
}
By using the Flags attribute, you can perform bitwise manipulation on the enumeration, to check and see which color options where set.
To do this, I used a helper function called:
public static bool IsColored( ColorOptions color, ColorOptions myColor )
{
if( ( myColor & color ) != ColorTypes.None )
return true; //if the color was selected, return true
else
return false; //if the color wasn’t selected, return false
}
Putting it all together
So, now my ExecuteColor() method looks like
public static void ExecuteColor( ColorOptions options )
{
//For demo, check to see if each color was called, and write out True or False
string line = "The color {0} was set: {1}";
Console.WriteLine( string.Format( line, ColorOptions.Red, IsColored( ColorOptions.Red, options ) ) ); //Red
Console.WriteLine( string.Format( line, ColorOptions.Blue, IsColored( ColorOptions.Blue, options ) ) ); //Blue
Console.WriteLine( string.Format( line, ColorOptions.White, IsColored( ColorOptions.White, options ) ) ); //White
Console.WriteLine( string.Format( line, ColorOptions.Black, IsColored( ColorOptions.Black, options ) ) ); //Black
Console.WriteLine( string.Format( line, ColorOptions.Green, IsColored( ColorOptions.Green, options ) ) ); //Green
}
And this allows developers to call ExecuteColor() by setting 1 color, multiple colors, or no colors. Here are some example method calls
ExecuteColor( ColorOptions.Red ); //Set only Red
ExecuteColor( ColorOptions.Red | ColorOptions.White ); //set Red and White
ExecuteColor( ColorOptions.None ); //don't set any colors
ExecuteColor( ColorOptions.Green | ColorOptions.Black | ColorOptions.Blue ); //Set Green, Black, Blue
Cheers!
Dave