convert array of bool to enum flag in csharp

In C#, we can use the Enum class to create enums that have the Flags attribute. To convert an array of bool values to an enum flag value, we can use bitwise operations and the Enum.Parse method.

Here's an example implementation:

main.cs
[Flags]
public enum MyEnum {
    None = 0,
    Flag1 = 1 << 0,
    Flag2 = 1 << 1,
    Flag3 = 1 << 2,
    All = Flag1 | Flag2 | Flag3
}

public static MyEnum BoolArrayToEnumFlag(bool[] bools) {
    int flagValue = 0;
    for (int i = 0; i < bools.Length; i++) {
        if (bools[i]) {
            flagValue |= 1 << i;
        }
    }
    return (MyEnum)flagValue;
}
368 chars
19 lines

In this example, we define an enum MyEnum with four values: None, Flag1, Flag2, Flag3, and All. The Flags attribute indicates that these values can be combined using bitwise OR operations.

The BoolArrayToEnumFlag method takes an array of bool values as input and converts it to an enum flag value. It iterates over the array and sets the corresponding bit in the flagValue variable if the bool array has a true value at that index.

Finally, the method returns the enum value obtained by casting the flagValue integer to the MyEnum enum type using the Enum.Parse method.

gistlibby LogSnag