Question How to change with a loop the name of a function to be called

Mercy G

New member
Joined
Mar 10, 2021
Messages
2
Programming Experience
1-3
Hello everyone,
I have a Visual Studio project that has multiple void methods named Ex1(), Ex2(), Ex3(), ..., Ex8().
I would like to call them all in the Main function, one after the other, so that on the console I have the display of all the exercices successively.
Is it possible to create a loop (from 1 to 8) that changes the name of the method to "Ex"+the number, and calls that method ?
I tried this but it doesn't work :
C#:
string Exo;
for (int z = 1; z <= 8; z++)
{
     Exo = "Ex"+z;
     Exo();
}

Thank you for your help,
Martin
 
Unfortunately, unless you start using reflection, there isn't an easy way to do that because C# is an early bound language. It's not late bound like a lot of interpreted languages.

A relatively easy way to achieve what you want is to make a list of delegates and iterate over the list calling each one.
C#:
void Ex1() => Console.WriteLine("A");
void Ex2() => Console.WriteLine("B");
void Ex3() => Console.WriteLine("C");

void Run()
{
    var methods = new List<Action>()
    {
        Ex1,
        Ex2,
        Ex3,
    };

    foreach(var method in methods)
        method();
}
 
Thanks for your quick and clear answer,
I see how you could do that, but you would still need to write all the names individually, which would defeat the purpose of the function...
I guess I'm trying to make my life a little too easy ?
Thanks again,
Martin
 
The amount of code you would need to do reflection plus the added uncertainty introduced by using reflection would be something you would need to weigh against the convenience of not having to list each method individually. The compiler can save you if you list a method that does not exist. If you compose the name of the method on the fly, and use reflection, you should have code that handles the case when the composed name does not have a corresponding method. (Alternatively, you could enumerate all methods using reflection and only call the methods that match a particular pattern.)
 
Using Reflection to save yourself just a few lines of code is borderline insane. If you had hundreds of methods to call then I might see the case but for eight? The code you posted is already six lines so what are you really saving yourself? It's a false economy.
 
Back
Top Bottom