Wednesday, January 7, 2009

Flags Attribute For Enum

Really a very good functionality provided by “Flags Attribute” for Enum. When Enum mark with “Flags“ attribute it will work as bit field.
Here i am going to explain Enum with and without Flags Attribute.

// Enum Without Flags Attribute.
public enum Simple : int
            UserRead =1,
            UserWrite = 2,
            UserExecute = 4,
            GroupRead = 8,
            GroupWrite = 16,
            GroupExecute = 32

//Enum With Flags Attribute
public enum WithFlagAttrib : int
            UserRead = 1,
            UserWrite = 2,
            UserExecute = 4,
            GroupRead=  8,
            GroupWrite = 16,
            GroupExecute = 32

In Above code Simple Enum is without attribute and in that i explicitly defined value for each of Enum. (That is just for compare both of them in same scenario).

Now Simple Example Test

int result = (int)(Simple.UserRead | Simple.UserWrite | Simple.GroupRead))
Console.WriteLine(result.ToString()); // output 11

Now value to enum

Console.WriteLine(((Simple)result).ToString()); // output 11. It will not converted to enum as none of the value is associated with 11.
In some scenario when Enum converted to value and stored in database and when it retrieve back from database , we want to convert it to Enum. This is where “Flags Attribute” real usage comes into picture.

Now With Flags Attribute Enum

int result = (int)(WithFlagAttrib.UserRead | WithFlagAttrib.UserWrite | WithFlagAttrib.GroupRead)).ToString();
Console.WriteLine(result.ToString()); // output 11

Now value to Enum

Console.WriteLine(((WithFlagAttrib)result).ToString()); // It will produce output UserRead , UserWrite , GroupRead. This is what we needed.

In both of the case when bitwise operation done at first place it produce same output but when convert value to Enum then Enum with “Flags Attribute” show right result b’coz it use bit as usage.

One thing keep into mind that when Enum create with “Flags Attribute” always assign value power of 2 starting from 1. like 1,2,4,8,16,32,64,128. (Actually it shows which bit is used for particular enum operation and it also limit this type of enum with no criteria it contains).

// For Value (11)
11 (32 bit binary value) : 00000000000000000000000000001011

Bit Position 32 16 8 4 2 1
Enum GroupExecute GroupWrite GroupRead UserExecute UserWrite UserRead
Value 0 0 1 0 1 1

Only used few bits in above table to display value 11. Now you get idea that which ever bit is on it produce in result.

For Example :
int val = 12;
// 12 binary number  00000000000000000000000000001100. So output is GroupRead , UserExecute.

Let me know if you have any question or comment on this.

Note : When you search this thing MSDN please make sure that Enum mark with “Flags Attribute “  start with value 1 not by 0.

No comments: