Search code examples
c#.netenumsenum-flags

Best practice for checking for an enum flag


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


Solution

  • .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