Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a function from a variable in C#

Is there any way so that you can call a function with a variable?

variable+"()";

or something like that, or would I have to use if statements?

A switch seems like it might be the answer, so if the variable's value=var1 I want it to execute var1(); if the value is var2 I want it to execute var2(); how would I code it?

Basically, I am trying to find a cleaner alternative to

if (variable == var1)
{
var1();
}
if (variable == var2)
{
var2();
}
like image 230
Sean Avatar asked Nov 30 '22 09:11

Sean


2 Answers

It would be possible to use reflection to find a method in an object and call that method, but the simplest and fastest would be to simply use a switch:

switch (variable) {
  case "OneMethod": OneMethod(); break;
  case "OtherMethod": OtherMethod(); break;
}
like image 79
Guffa Avatar answered Dec 20 '22 05:12

Guffa


You could use Reflection http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx to access any function or member by name. It takes some getting used to though. It also has performance issues, so if you can avoid using it, you should.

like image 44
C.Evenhuis Avatar answered Dec 20 '22 06:12

C.Evenhuis