Search code examples
c#enumsswitch-statementbitflags

How to make [Flags] enum and switch case work together?


How to make [Flags] enum and switch case work together? Very desirable to make it looks simple. Similar Questions asked many times, but never directly to [Flags] enum.

If M1 set execute operation 1,

if M2 set execute operation2 ,

if BOTH M1 and M2 then set execute operation 1 and 2.

 [Flags]
    public enum TST
    {
        M1 =1,
        M2 =2,
        M3 =4
    }

 public void PseudoCode()
    {

        TST t1 = TST.M1 | TST.M3; //1+2= 3

        switch( t1)
        {
            case TST.M1:
                {
                    //Do work if Bit 1 set
                }
            case TST.M2:
                {
                    //Do work if Bit 2 set
                }
            case TST.M3:
                {
                    //Do work if Bit 3 set
                }
            default:
                {
                    //nothing set;
                    break;
                }
        }

    }

I also quite sure a lot of people want to know how to make it work. Request fix of C#?


Solution

  • This will execute for any bit set

    for example

    ExecuteOnFlagValue(TST.M1 | TST.M3); //1+2= 3
    

    Will execute code for bits 1 and 3

    public void ExecuteOnFlagValue(TST value) {
        if (value & TST.M1 == TST.M1) {
            //Do work if bit 1
        }
        if (value & TST.M2 == TST.M2) {
            //Do work if bit 2
        }
        if (value & TST.M3 == TST.M3) {
            //Do work if bit 3
        }
    }