Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for checking for an enum flag [closed]

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

like image 207
Mohammed Ali Avatar asked May 13 '12 18:05

Mohammed Ali


4 Answers

.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
like image 50
Kamyar Nazeri Avatar answered Nov 04 '22 14:11

Kamyar Nazeri


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.

like image 42
Tigran Avatar answered Nov 04 '22 14:11

Tigran


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)
like image 1
David Heffernan Avatar answered Nov 04 '22 14:11

David Heffernan


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.

like image 1
John Alexiou Avatar answered Nov 04 '22 16:11

John Alexiou