Let's say I've got 6 methods: Method1(), Method2(), Method3(), Method4(), Method5() and Method6(). I also have another method, SuperMethod(int nr), that will call one of the other methods. If the input to SuperMethod is 1, Method1() will be called and so on.
Can this be done in an elegant way without having a switch statement or stacking if-else statements?
I should add that this is not important production code I'm writing, so performance is not an issue.
you can use delegates and it is also interesting for solving real world problems with short programs:
public void CollatzTest(int n)
{
var f = new Func<int, int>[] { i => i / 2, i => i * 3 + 1 };
while (n != 1)
n = f[n % 2](n);
}
that also works with actions, and direct method references
private void DelegateActionStartTest()
{
Action[] Actions = new Action[] { UselesstTest, IntervalTest, Euler13 };
int nFunction = 2;
Actions[nFunction]();
}
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