Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function using a parameter in it's name

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

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 function with the name "Level" and the index number.

like image 978
Ori Frish Avatar asked Jul 03 '26 21:07

Ori Frish


2 Answers

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.)

like image 75
Jon Skeet Avatar answered Jul 06 '26 12:07

Jon Skeet


Try this:

typeof(yourClassCOntainingLevel1Method).GetMethod("Level"+index).Invoke(this,null); 

yourClassCOntainingLevel1Method is a class name where you have Level1 method

if it's in the same class as calling:

typeof(this).GetMethod("Level"+index).Invoke(this,null); 
like image 29
Kamil Budziewski Avatar answered Jul 06 '26 11:07

Kamil Budziewski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!