Large flags enumerations in C#

LorenVS picture LorenVS · May 8, 2010 · Viewed 9.8k times · Source

Hey everyone, got a quick question that I can't seem to find anything about...

I'm working on a project that requires flag enumerations with a large number of flags (up to 40-ish), and I don't really feel like typing in the exact mask for each enumeration value:

public enum MyEnumeration : ulong
{
    Flag1 = 1,
    Flag2 = 2,
    Flag3 = 4,
    Flag4 = 8,
    Flag5 = 16,
    // ...
    Flag16 = 65536,
    Flag17 = 65536 * 2,
    Flag18 = 65536 * 4,
    Flag19 = 65536 * 8,
    // ...
    Flag32 = 65536 * 65536,
    Flag33 = 65536 * 65536 * 2
    // right about here I start to get really pissed off
}

Moreover, I'm also hoping that there is an easy(ier) way for me to control the actual arrangement of bits on different endian machines, since these values will eventually be serialized over a network:

public enum MyEnumeration : uint
{
    Flag1 = 1,     // BIG: 0x00000001, LITTLE:0x01000000
    Flag2 = 2,     // BIG: 0x00000002, LITTLE:0x02000000
    Flag3 = 4,     // BIG: 0x00000004, LITTLE:0x03000000
    // ...
    Flag9 = 256,   // BIG: 0x00000010, LITTLE:0x10000000
    Flag10 = 512,  // BIG: 0x00000011, LITTLE:0x11000000
    Flag11 = 1024  // BIG: 0x00000012, LITTLE:0x12000000
}

So, I'm kind of wondering if there is some cool way I can set my enumerations up like:

public enum MyEnumeration : uint
{
     Flag1 = flag(1), // BOTH: 0x80000000
     Flag2 = flag(2), // BOTH: 0x40000000
     Flag3 = flag(3), // BOTH: 0x20000000
     // ...
     Flag9 = flag(9), // BOTH: 0x00800000
}

What I've Tried:

// this won't work because Math.Pow returns double
// and because C# requires constants for enum values
public enum MyEnumeration : uint
{
    Flag1 = Math.Pow(2, 0),
    Flag2 = Math.Pow(2, 1)
}

// this won't work because C# requires constants for enum values
public enum MyEnumeration : uint
{
    Flag1 = Masks.MyCustomerBitmaskGeneratingFunction(0)
}

// this is my best solution so far, but is definitely
// quite clunkie
public struct EnumWrapper<TEnum> where TEnum
{
    private BitVector32 vector;
    public bool this[TEnum index]
    {
         // returns whether the index-th bit is set in vector
    }
    // all sorts of overriding using TEnum as args
}

Just wondering if anyone has any cool ideas, thanks!

Answer

Kelsey picture Kelsey · May 8, 2010

Why not just do:

public enum MyEnumeration : ulong 
{ 
    Flag1 = 1, 
    Flag2 = 1 << 1, 
    Flag3 = 1 << 2, 
    Flag4 = 1 << 3, 
    .
    .
    .
    Flag30 = 1 << 29, 
    Flag31 = 1 << 30, 
    Flag32 = 1 << 31
}