Dobkin's Place

Friday, September 01, 2006

Flags Attribute

Introduction:
Some times when you have an Enum, you want to relate each combination of elements as a different value, this functionality can be achieved by represent each element as a multiple by two (1, 2, 4, 8, 16 etc), that way when you connect couple of elements with the binary OR operator ("") each combination get different number.

In case you have such an Enum you cam easily add nice functionality to it, by editing the [Flags] attribute.
Let see in simple example what it does.

[Flags]
public enum Colors
{
Red = 1,
Green = 2,
Blue = 4,
Black = 8,
White = 16,
Purple = 32
}

class MyClass
{
static void Main(string[] args)
{
Colors c = (Colors)17;
Console.WriteLine(
"The Colors are: {0}", c);
}
}

The output of this piece of code would be:
"The Colors are: Red, White"

What this functionality good for?

It can be used as descriptive pattern. A calculated number of the chosen colors can be stored in Database, for instance, and next time when this number would be retrieved, a list of the selected colors names can be display, like shown in the example above.

0 Comments:

Post a Comment

<< Home