Connecting Tech Pros Worldwide Forums | Help | Site Map

Call a function whose name is stored in a string?

Hugh
Guest
 
Posts: n/a
#1: Nov 15 '05
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



Bret Mulvey [MS]
Guest
 
Posts: n/a
#2: Nov 15 '05

re: Call a function whose name is stored in a string?


"Hugh" <hyoo@softhome.net> wrote in message
news:eMpypOemDHA.2232@TK2MSFTNGP09.phx.gbl...[color=blue]
> Hi all,
>
> Is it possible to execute a function by getting the name of the function[/color]
to[color=blue]
> execute from a string? For example:
>
> string FunctionName = "MyFunction";
>
> which would execute MyFunction().
>[/color]

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);
}
}



Closed Thread