Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling methods by number

Tags:

c#

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.

like image 881
haagel Avatar asked Apr 26 '26 12:04

haagel


1 Answers

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]();
    }
like image 104
user287107 Avatar answered Apr 28 '26 04:04

user287107