Tuesday 20 June 2017

Flags attribute

When you create an Enum you can add the [Flags] attribute if you want to use it as a bit mask. for example lets say you where running a food stand at the beach and you where selling:

ItemDecimalBinary
Pop10000001
Chips20000010
CandyBar40000100
Gyro80001000
Shwarma160010000
Pizza320100000
Pop641000000

Now that we have our values if we where to have a bitwise OR on any combination of products lets, do pop and chips we'd get: 01 or 10 = 11; 11 being the binary equivalent of 3. the significance of this is as follows

using System;

namespace EnumExample
{
    class Program
    {
        [Flags]
        enum Food : short
        {
            Pop = 1, Chips = 2, CandyBar = 4, Gyro = 8, Shwarma = 16, Pizza = 32, Spuds = 64
        }

        static void Main(string[] args)
        {
            var f1 = Food.Chips;//01
            var f2 = Food.Pop; //10

            Console.WriteLine($"{f1} has a value of {(short)f1}");
            Console.WriteLine();
            Console.WriteLine($"{f2} has a value of {(short)f2}");
            Console.WriteLine();
            Console.WriteLine($"{f1 | f2} have a value of {(short)(f1 | f2)}");
        }
    }
}


now the result is


if we didn't decorate our enum with the [Flags] attribute, when we tried to do a bit-wise OR on f1 and f2 we'd just get the numeric value of three, but because we used the [Flags] attribute we see Pop, Chips instead.