C# ASP.NET SQL SERVER

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.

 

» Similar Posts

  1. Automatically keeping CSS file current on any web page
  2. ASP.NET MVC DropDownList from Enum
  3. Combine, compress, and update your CSS file in ASP.NET MVC

» Trackbacks & Pingbacks

    No trackbacks yet.
Trackback link for this post:
http://guyellisrocks.com/trackback.ashx?id=231

» Comments

    There are no comments. Kick things off by filling out the form below.

» Leave a Comment