I noticed these two patterns for checking for an enum flag:
[Flags]
public enum PurchaseType
{
None = 0,
SalePrice = 2,
RegularPrice = 4,
Clearance = 8,
CreditCard = 16
}
public void Test()
{
PurchaseType type = PurchaseType.Clearance;
type |= PurchaseType.CreditCard;
// Practice 1
if ((type & PurchaseType.Clearance) == PurchaseType.Clearance)
{
// Clearance item handling
}
// Practice 2
if ((type & PurchaseType.CreditCard) != 0)
{
// Credit card item handling
}
}
Of the two ways of checking for an enum flag, which one is better w.r.t performance, readability, code health, and any other considerations I should make?
Thanks, Mohammed
.Net 4 introduces a HasFlag
method that determines whether one or more bit fields are set in the current instance, this is by far the best practice:
type.HasFlag(PurchaseType.CreditCard); // true
I would choose the first one:
if ((type & PurchaseType.Clearance) == PurchaseType.Clearance)
{
// Clearance item item handling
}
cause it clearly clams that you're checking for Clearance
type presence.
I personally would always prefer the clear readability of HasFlag
.
However, out of the two options in the question I think !=0
is safer because it has no duplication. If you use your alternative then it's all too easy when maintenence coding to change one of of the flags and forget to change the other. And then you end up with this
if ((type & PurchaseType.Clearance) == PurchaseType.CreditCard)
I would prefer (type & PurchaseType.CreditCard) != 0
because if you want to check for more than one bit then the right hand side becomes cumbersome. I trust in bit operations that the above will only be true if and only if the bit(s) is set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With