Call a function whose name is stored in a string?

  • Thread starter Thread starter Hugh
  • Start date Start date
H

Hugh

Hi all,

Is it possible to execute a function by getting the name of the function to
execute from a string? For example:

string FunctionName = "MyFunction";

which would execute MyFunction().

Any help appreciated,
Cheers, Hugh
 
Hugh said:
Hi all,

Is it possible to execute a function by getting the name of the function to
execute from a string? For example:

string FunctionName = "MyFunction";

which would execute MyFunction().

Yes. Here's an example that calls System.Random.NextDouble, where the method
name "NextDouble" comes from a string.

class Class1
{
static Random rand = new Random();

static void Main(string[] args)
{
string methodName = "NextDouble";
System.Reflection.MethodInfo info =
rand.GetType().GetMethod(methodName);
double r = (double) info.Invoke(rand, null);
}
}
 
Back
Top