Bit flags and Switch instruction?

I have the following code (example), and I'm really uncomfortable with many if checks:

public enum Flags { p1 = 0x01, // 0001 p2 = 0x02, // 0010 p3 = 0x04, // 0100 p4 = 0x08 // 1000 }; public static void MyMethod (Flags flag) { if ((flag & Flags.p1) == Flags.p1) DoSomething(); if ((flag & Flags.p2) == Flags.p2) DosomethingElse(); if ((flag & Flags.p3) == Flags.p3) DosomethingElseAgain(); if ((flag & Flags.p4) == Flags.p4) DosomethingElseAgainAndAgain(); } MyMethod(Flags.p1 | Flags.p3); 

Is there any way that I can use the switch statement. Maybe if I convert them to strings or use arrays?

+6
enums c # bit-manipulation switch-statement
source share
2 answers

Something like that?

 public static void MyMethod(Flags flag) { // Define action-lookup var actionsByFlag = new Dictionary<Flags, Action> { { Flags.p1, DoSomething}, { Flags.p2, DosomethingElse}, { Flags.p3, DosomethingElseAgain}, { Flags.p4, DosomethingElseAgainAndAgain}, }; // Find applicable actions var actions = actionsByFlag.Where(kvp => (flag & kvp.Key) == kvp.Key) .Select(kvp => kvp.Value); //Execute applicable actions foreach (var action in actions) action(); } 

EDIT: If order is important, an OrderBy clause may be required.

+7
source share

Here is an Ani answer option:

 public static void MyMethod(Flags flag) { // Define action-lookup var dict = new Dictionary<Flags, Action> { { Flags.p1, DoSomething}, { Flags.p2, DosomethingElse}, { Flags.p3, DosomethingElseAgain}, { Flags.p4, DosomethingElseAgainAndAgain}, }; // Find applicable actions var actions = from value in Enum.GetValues(typeof(Flags)) where flag.HasFlag(value) select dict[value]; //Execute applicable actions foreach (var action in actions) action(); } 

An important difference here is that it iterates over certain values ​​in an enumeration, rather than entries in a dictionary. Thus, if you add a new flag to the enumeration without adding it to the dictionary, you will get an exception when you try to use the new flag. And it always iterates in order of flags.

+6
source share

All Articles