Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 4
System
Enum Class
Enum Methods
 HasFlag Method
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2010/.NET Framework 4

Other versions are also available for the following:
.NET Framework Class Library
Enum..::.HasFlag Method

Determines whether one or more bit fields are set in the current instance.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)
Visual Basic
Public Function HasFlag ( _
    flag As Enum _
) As Boolean
C#
public bool HasFlag(
    Enum flag
)
Visual C++
public:
bool HasFlag(
    Enum^ flag
)
F#
member HasFlag : 
        flag:Enum -> bool 

Parameters

flag
Type: System..::.Enum
An enumeration value.

Return Value

Type: System..::.Boolean
true if the bit field or bit fields that are set in flag are also set in the current instance; otherwise, false.
ExceptionCondition
ArgumentException

flag is a different type than the current instance.

The HasFlag method returns the result of the following Boolean expression.

thisInstance And flag = flag 

If the underlying value of flag is zero, the method returns true. If this behavior is not desirable, you can use the Equals method to test for equality with zero and call HasFlag only if the underlying value of flag is non-zero, as the following example illustrates.

Visual Basic
<Flags> Public Enum Pet
   None = 0
   Dog = 1
   Cat = 2
   Bird = 4
   Rabbit = 8
   Other = 16
End Enum

Module Example
   Public Sub Main()
      Dim petsInFamilies() As Pet = { Pet.None, Pet.Dog Or Pet.Cat, Pet.Dog }
      Dim familiesWithoutPets As Integer
      Dim familiesWithDog As Integer

      For Each petsInFamily In petsInFamilies
         ' Count the number of families that have no pets.
         If petsInFamily.Equals(Pet.None) Then
            familiesWithoutPets += 1 
        ' Of families that have pets, count the number of families with a dog.
         Else If petsInFamily.HasFlag(Pet.Dog) Then
            familiesWithDog += 1
         End If
      Next
      Console.WriteLine("{0} of {1} families in the sample have no pets.", 
                        familiesWithoutPets, petsInFamilies.Length)   
      Console.WriteLine("{0} of {1} families in the sample have a dog.", 
                        familiesWithDog, petsInFamilies.Length)   
   End Sub
End Module
' The example displays the following output:
'       1 of 3 families in the sample have no pets.
'       2 of 3 families in the sample have a dog.
C#
using System;

[Flags] public enum Pet {
   None = 0,
   Dog = 1,
   Cat = 2,
   Bird = 4,
   Rabbit = 8,
   Other = 16
}

public class Example
{
   public static void Main()
   {
      Pet[] petsInFamilies = { Pet.None, Pet.Dog | Pet.Cat, Pet.Dog };
      int familiesWithoutPets = 0;
      int familiesWithDog = 0;

      foreach (Pet petsInFamily in petsInFamilies)
      {
         // Count families that have no pets.
         if (petsInFamily.Equals(Pet.None))
            familiesWithoutPets++;
         // Of families with pets, count families that have a dog.
         else if (petsInFamily.HasFlag(Pet.Dog))
            familiesWithDog++;
      }
      Console.WriteLine("{0} of {1} families in the sample have no pets.", 
                        familiesWithoutPets, petsInFamilies.Length);   
      Console.WriteLine("{0} of {1} families in the sample have a dog.", 
                        familiesWithDog, petsInFamilies.Length);   
   }
}
// The example displays the following output:
//       1 of 3 families in the sample have no pets.
//       2 of 3 families in the sample have a dog.

The HasFlag method is designed to be used with enumeration types that are marked with the FlagsAttribute attribute. For enumeration types that are not marked with the FlagsAttribute attribute, call either the Equals method or the CompareTo method.

The following example defines an ItemsOrdered enumeration that reflects categories of items that a customer can order in a restaurant. The example tests whether the customer has ordered both an entrée and a beverage.

Visual Basic
<Flags> Public Enum DinnerItems As Integer
   None = 0
   Entree = 1
   Appetizer = 2
   Side = 4
   Dessert = 8
   Beverage = 16 
   BarBeverage = 32
End Enum

Module Example
   Public Sub Main()
      Dim myOrder As DinnerItems = DinnerItems.Appetizer Or DinnerItems.Entree Or
                                   DinnerItems.Beverage Or DinnerItems.Dessert
      Dim flagValue As DinnerItems = DinnerItems.Entree Or DinnerItems.Beverage
      Console.WriteLine("{0} includes {1}: {2}", 
                        myOrder, flagValue, myOrder.HasFlag(flagValue))
   End Sub
End Module
' The example displays the following output:
'    Entree, Appetizer, Dessert, Beverage includes Entree, Beverage: True
C#
using System;

[Flags] public enum DinnerItems {
   None = 0,
   Entree = 1,
   Appetizer = 2,
   Side = 4,
   Dessert = 8,
   Beverage = 16, 
   BarBeverage = 32
}

public class Example
{
   public static void Main()
   {
      DinnerItems myOrder = DinnerItems.Appetizer | DinnerItems.Entree |
                            DinnerItems.Beverage | DinnerItems.Dessert;
      DinnerItems flagValue = DinnerItems.Entree | DinnerItems.Beverage;
      Console.WriteLine("{0} includes {1}: {2}", 
                        myOrder, flagValue, myOrder.HasFlag(flagValue));
   }
}
// The example displays the following output:
//    Entree, Appetizer, Dessert, Beverage includes Entree, Beverage: True

.NET Framework

Supported in: 4

.NET Framework Client Profile

Supported in: 4

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
More info on performance      ChrisLaMont   |   Edit   |   Show History
The performance issue is likely due to the boxing/unboxing that occurs with this method. For more information on this issue, and examples on how to implement a more efficient version view the following link

http://stackoverflow.com/q/7984377/328397
Tags What's this?: Add a tag
Flag as ContentBug
Efficiency warning      Rick Sladkey ... ChrisLaMont   |   Edit   |   Show History
A user of this method should be aware that the current implementation is painfully slow, approximately 1000 times slower than manually inlining the code that the method is defined to expand into, and therefore use in performance critical code is not recommended. $0$0 $0 $0$0 $0 $0//<todo: put example of more efficient method here> $0
Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2012 Microsoft. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker