Everything about my daily life as a programmer/Electrical Engineer!

Flag enums

I was working on a project that needed to use flag enums to store state.  Flag enums are great, except after 2^15 the numbers get hard to calculate. I resorted to using excel to generate the enum code for me, that is until I learned I can do math expressions inside of enums! What I forgot is that 2^0 is not equivalent to Math.Pow(2,0).  This is when I discovered my old friend shift.

 

 

using System;

namespace TestEnum
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(oldway.All);
Console.WriteLine(newway.All);
}
}

[Flags]
enum oldway
{
None=0,
One=1,
Two=2,
Three=4,
Four=8,
All=15
}

[Flags]
enum newway
{
None = 0,
One = 1<<0,
Two = 1<<1,
Three = 1<<2,
Four = 1<<3,
All = (1<<4) - 1
}
}

 


As you can see they both work the same :)


image

No comments: