Monday, January 4, 2010

Flags enum attribute

I've just learned about the [Flags] attribute for enums. I'm surprised that I hadn't stumbled across it before. Consider the following code snippet:

enum Direction { North = 1, East = 2, South = 4, West = 8 }
static void EnumTesting()
{
    Direction ne = Direction.North | Direction.East;
    Console.WriteLine(ne);
}

The output is: 3

Now add the [Flags] attribute to the enum:

[Flags]
enum Direction { North = 1, East = 2, South = 4, West = 8 }
static void EnumTesting()
{
    Direction ne = Direction.North | Direction.East;
    Console.WriteLine(ne);
}

The output is now: North, East

Enumeration constants are generally used for lists of mutually exclusive elements. However, sometimes you may want to use them for lists of elements that might occur in combination. Permissions to access resources is a good example of this.

 

No comments:

Post a Comment