Search code examples
c#enumsparametersbitwise-andbitflags

Is there any reason to use enum params over bit flags in c#?


Lets say, for example, I have two implementations, one with bit flags and one with simple enum:

1) bit flags

[Flags]
public enum LettersBitFlags
{
    A = 1,
    B = 2,
    C = 4,
    D = 8
}
public static bool IsLetterBBitFlags(LettersBitFlags letters)
{
    return (letters & LettersBitFlags.B) != 0;
}

2) simple enum

public enum Letters
{
    A,
    B,
    C,
    D
}
public static bool IsLetterBParams(params Letters[] letters)
{
    return letters.Any(x => x == Letters.B);
}

They obviously can be used like this:

Console.WriteLine(IsLetterBBitFlags(LettersBitFlags.A | LettersBitFlags.D)); //false
Console.WriteLine(IsLetterBBitFlags(LettersBitFlags.B | LettersBitFlags.C)); //true

Console.WriteLine(IsLetterBParams(Letters.A, Letters.D)); //false
Console.WriteLine(IsLetterBParams(Letters.B, Letters.C)); //true

Is there any practical reason to choose one over the other? As I see, they give the same result, but maybe some performance or anything else should make me use one and did not use the other?


Solution

  • They have different meanings. Flags are characterised by the fact that it's meaningful to OR them together; enums are simply discrete lumps of data, and the fact that they are numerical under the covers is nothing more than an implementation detail.

    If you use flags where it's not meaningful to OR two of them together, you will badly mislead anyone who comes to use your data type. Conversely, if you use an enum where you meant a flag, then you'll have to manually capture and name exponentially many enum cases.