Tuesday, November 3, 2009

Flags Attribute

Introduction

Flags attribute is useful C# feature that allows treating of enumeration members as bit fields, therefore to combine multiple options within single enum variable by using bitwise OR operation.

Example

We simply decorate our enum with Flags attribute and assign to each member number that follows base 2 sequence like 1, 2, 4, 8 and so on:


[Flags]
public enum MoneyPart
{

A = 1,
B = 2,
C = 4
}


Combine the appropriate options:


MoneyPart moneyPartVar = MoneyPart.A | MoneyPart.B;


Now we can add a method that receives MoneyPart variable and checks its value by using bitwise AND operation:


private decimal CalculatePolicyRedemption(MoneyPart moneyParts)
{
decimal total = 0M;
if ((moneyParts & MoneyPart.A) != 0)
{
total += 100;
}
if ((moneyParts & MoneyPart.B) != 0)
{
total += 200;
}
if ((moneyParts & MoneyPart.C) != 0)
{
total += 300;
}

return total;
}


Isn't it handy feature? :)

Mark.

No comments:

Post a Comment