How to use flag enuemeration in c#/asp.net

Imagine we have a User class, and one of the user properties is Permission. The Permission enum can be defined as follows:
enum Permission
    {
        None = 0,
        Read = 2,
        Write = 4,
        ReadWrite = 8,
        All = Int16.MaxValue

    }
As you can see -these options could be combined in several ways like an user can have Read and Write permission or user can have only Read permission.Most of us will create seprate properties in user class but efficient way to resolve this problem is use flag enumeration.flag enumeration is an instance of the enumeration type to store any combination of the values that are defined in the enumerator list.You create a bit flags enum by applying the System.FlagsAttribute attribute and defining the values appropriately so that AND, OR, NOT and XOR bitwise operations can be performed on them.
[Flag]
  enum Permission
    {
        None = 0,
        Read = 2,
        Write = 4,
        ReadWrite = 8,
        All = Int16.MaxValue

    }

or

 [Flag]
  enum Permission
    {
        None = 0x,
        Read = 1x,
        Write = 2x,
        ReadWrite = 3x,
        All = Int16.MaxValue

    }

This means we can now use the bitwise OR|AND|NOT|XOR operator to combine these enum values. For instance:How to set a flag on an enum, use the bitwise OR operator as shown in the following example:

Permission permisson = Permission.Read | Permission.Write;
How to reset a flag on an enum

permisson &= ~Permission.Read;
How to filp a flag on an enum

permisson &= ~Permission.Read;
How to clear all flags

permission=Permission.None

1 comment:

  1. Hey santosh

    Nice article ...
    i have used this type enum and bitwise operator for saving values of different checkboxes(check or uncheck) on a single page, in database using single field in table.

    Nice wayout
    keep it up

    ReplyDelete