C# Alternatives – What to Use Instead of Bitwise Flags

cnet

I was trying to be smart and elegant, and I ended up shooting myself in the foot by coding my entire application to use flags to store various combinations of settings.

Now, I have hit a point where I have > 64 options. I need to move away from flags or I will be forced to create additional fields, which will make my application really messy given its current state.

What should I consider as an alternative to using flags other than creating a separate boolean variable for each option?

Update

By flags, I mean bitwise flags, e.g.:

[Flags]
public enum Time
{
    None = 0
    Flag1 = 1,
    Flag2 = 2,
    Flag3 = 4,
    // ...
    Flag63 = ...
}

Best Answer

You could use a BitArray in conjunction with static fields to provide labels for the bits:

static class Flags
{
  public static int WorkProperly = 0;
  public static int CompileFaster = 1;
  public static int AutoImproveCodeQuality = 2;
}

class FlagTest
{
  static void Main(string[] args)
  {
    BitArray bits = new BitArray(100); // > 64
    bits[Flags.AutoImproveCodeQuality] = true;
  }
}

Or, with an enum, but you'd have to cast the value every time:

enum Flags
{
  Never = 0,
  MostOfTheTime,
  Sometimes,
  OddThursdays,
  WhenPigsFly
}

...

BitArray bits = new BitArray(1000); // lots of bits
bits[(int)Flags.Sometimes] = true;
Related Topic