How to use flag Enum 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 a user can have Read and Write permission, or a user can have only Read permission.

Most of us will create separate properties in the user class, but an efficient way to resolve this problem is using flag enumeration. Flag enumeration is an instance of the enumeration type to store any combination of the values defined in the enumerator list.

You create a bit of 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.

[System.FlagsAttribute]
enum Permission
{
	None = 0,
	Read = 2,
	Write = 4,
	ReadWrite = 8,
	All = Int16.MaxValue

}

Another way to declare is as shown below``

 [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 flip a flag on an enum

permisson &= ~Permission.Read;

How to clear all flags

permission=Permission.None

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post