Use Enums for Bitwise Operation with Flags attribute

You may want to tag your enums with [Flags] should you need to tackle different permutation/combination using bitwise operation.Find the code below I put together quick as a sample…
class Test
{
[Flags]
public enum AccessRightsStates
{
Read = 1 << 0, //1,
Edit = 1 << 1, //2,
Publish = 1 << 2, //4,
Admin = 1 << 3 //8
}
static void Main(string[] args)
{
int combinedState = (int)(AccessRightsStates.Read | AccessRightsStates.Edit | AccessRightsStates.Admin);
Console.WriteLine("Combined State value = {0}", combinedState.ToString());
Console.WriteLine("Read state is {0}", ContainsState((AccessRightsStates)combinedState, AccessRightsStates.Read));
Console.WriteLine("Edit state is {0}", ContainsState((AccessRightsStates)combinedState, AccessRightsStates.Edit));
Console.WriteLine("Publish state is {0}", ContainsState((AccessRightsStates)combinedState, AccessRightsStates.Publish));
Console.WriteLine("Admin state is {0}", ContainsState((AccessRightsStates)combinedState, AccessRightsStates.Admin));
Console.ReadLine();
}
public static bool ContainsState(AccessRightsStates combinedstate, AccessRightsStates againststate)
{
return ((combinedstate & againststate) == againststate);
}
}

Prakash Software Solutions PVT LTD. Offer wide range of services to their clients all over the globe. We successfully delivered projects i.e. software development, cloud computing solutions, SharePoint development solutions, mobile app development and Microsoft technology solution to our Sweden, Denmark, Netherlands, France, Norway, Germany, Spain, Italy, Switzerland, Belgium, Luxembourg, Ireland, United Kingdom, United States, Canada, Brazil, Peru, UAE, Dubai, Saudi Arabia, Kuwait, Qatar, Bahrain, Singapore, New Zealand and Australia Clients.

Related Posts

Leave a reply