Software Architecture – C# 4-0 – New Feature – enum – HasFlag()

In C# 4.0, enum has a new function as:
public bool HasFlag(Enum flag )

which takes second enum as parameter and return bool as true if the bit field or bit fields that are set in flag are also set in the current instance; otherwise, false.

Logically HasFlag evaluates following expression:

thisInstance And flag = flag

Lets declare a enum for colors as:

[Flags]
        enum ColorShade
        {
            NoColor = 0,     // 
            Red = 1,
            Blue = 2,
            Green = 4,
            Black = 8,
            Grey = 16,
            Pink = 32
        }  

Lets perform some testing as:

ColorShade ColA = ColorShade.Blue | ColorShade.Green | ColorShade.Black;
        ColorShade ColB =  ColorShade.Blue | ColorShade.Black   ;
        ColorShade ColC =  ColorShade.Black | ColorShade.Pink ;
        Console.WriteLine("ColA: {0}", ColA);   //  ColA: Blue, Green, Black
        Console.WriteLine("ColB: {0}" , ColB);  // ColB: Blue, Black
        Console.WriteLine("ColC: {0} " , ColC); // ColC: Black, Pink
        Console.WriteLine("ColA has ColB : {0} ", ColA.HasFlag(ColB));  // ColA has ColB : True
        Console.WriteLine("ColA has ColC : {0} ", ColA.HasFlag(ColC));  // ColA has ColC : False
        Console.WriteLine("ColB has ColA : {0} ", ColB.HasFlag(ColA));  //ColB has ColA : False
        Console.WriteLine("ColB has ColC : {0} ", ColB.HasFlag(ColC));  //ColB has ColC : False
        Console.WriteLine("ColC has ColA : {0} ", ColC.HasFlag(ColA));  //ColC has ColA : False
        Console.WriteLine("ColC has ColB : {0} ", ColC.HasFlag(ColB));  //ColC has ColB : False
        Console.ReadLine();

                    /*
                     * Output of Whole Program as:
                     * 
                    ColA: Blue, Green, Black
                    ColB: Blue, Black
                    ColC: Black, Pink
                    ColA has ColB : True
                    ColA has ColC : False
                    ColB has ColA : False
                    ColB has ColC : False
                    ColC has ColA : False
                    ColC has ColB : False
                            */

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: