Calling a function using a parameter in it's name

I've got a bit of strange question, I'll show you my code first, and then I'll ask the question.

I have this switch function:

switch(index)
    {
        case 1:
        Level1();
        break;
        case 2:
        Level2();
        break;
        case 3:
        Level3();
        break;
        case 4:
        Level4();
        break;
        case 5:
        Level5();
        break;
    }

as you can see, each index calls a fcuntion with the name "Level" and the index number.

Can I put all of this code in one line, like "Level + index ()" Is it possible?

Jon Skeet
people
quotationmark

Not like that, no. You could use delegates:

// Ideally make this a readonly field.
Action[] actions = { Level1, Level2, Level3, Level4, Level5 };
...
actions[index - 1]();

Or you could use reflection, as others have mentioned... but I'd try to avoid that if possible, especially if performance is a concern.

It does feel like an odd design though - I'd take a step back and consider whether there's a cleaner way of designing this to start with. (It's hard for us to help with that at the moment without more context.)

people

See more on this question at Stackoverflow