C# Enum HasFlag

Description

Enum HasFlag determines whether one or more bit fields are set in the current instance.

Syntax

Enum.HasFlag has the following syntax.


public bool HasFlag(
  Enum flag
)

Parameters

Enum.HasFlag has the following parameters.

  • flag - An enumeration value.

Returns

Enum.HasFlag method returns true if the bit field or bit fields that are set in flag are also set in the current instance; otherwise, false.

Example

Call HasFlag only if the underlying value of flag is non-zero.


//from w  w w  .  j a  va2 s  .c om
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 };

      foreach (Pet petsInFamily in petsInFamilies)
      {
         if (petsInFamily.Equals(Pet.None))
            Console.WriteLine("None"); 
         else if (petsInFamily.HasFlag(Pet.Dog))
            Console.WriteLine("Dog");   
      }
        
      
   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version