Check if one or more bit fields are set in CSharp

Description

The following code shows how to check if one or more bit fields are set.

Example


//w  w  w .j  a  v  a 2  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 »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var