check if enum flag is set in csharp

To check if an enum flag is set in C#, you can use the bitwise AND operator (&) to compare the enum value with the flag value. Here's an example:

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

// check if Flag2 is set
MyFlags value = MyFlags.Flag1 | MyFlags.Flag2 | MyFlags.Flag3;

if ((value & MyFlags.Flag2) == MyFlags.Flag2)
{
    // Flag2 is set
}
else
{
    // Flag2 is not set
}
316 chars
22 lines

In this example, the bitwise AND operation is performed between the value variable and the MyFlags.Flag2 enum value. If the result is equal to MyFlags.Flag2, it means that the Flag2 is set in the enum, and the condition is true. Otherwise, the Flag2 is not set in the enum, and the condition is false.

gistlibby LogSnag