According to anti-if campaign it is a best practice not to use ifs in our code. Can anyone tell me if it possible to get rid of the if in this piece of code ? (switch is also
A little late to the party, but combining the C# dictionary answers from MRFerocius and cletus gives the following implementation of bmargulies's answer:
private Dictionary data = new Dictionary {
{"foo", () => Console.WriteLine("Some logic here")},
{"bar", () => Console.WriteLine("something else here")},
{"raboof", () => Console.WriteLine("of course I need more than just WriteLine")},
}
public static void main(String[] args) {
data["foo"]();
}
Multiple actions can be composed:
There can be multiple calls to different methods, using multiline lambda syntax:
{"foobar", () => {
data["foo"]();
data["bar"]();
}
As Action is a delegate type, multiple methods can be attached to a single delegate instance and that delegate instance set as the value; they will be called sequentially when the delegate is invoked:
public static void main(String[] args) {
data["foobar"] = data["foo"] + data["bar"];
//This will invoke first data["foo"] then data["bar"]
data["foobar"]();
}
For methods not referenced via the dictionary, this can also be done in the collection initializer:
{"foobar", (Action)method1 + method2}