I have the following code (example), and I'm really not comfortable with so 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 some way, that i could use an 'switch' statement. Maybe if I convert them to strings, or use arrays?
Something like this?
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 the order of actions are important, an OrderBy
clause may be required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With