Skip to content
Advertisement

Calling a function from a string in C#

I know in php you are able to make a call like:

$function_name = 'hello';
$function_name();

function hello() { echo 'hello'; }

Is this possible in .Net?

Advertisement

Answer

Yes. You can use reflection. Something like this:

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);

With the above code, the method which is invoked must have access modifier public. If calling a non-public method, one needs to use the BindingFlags parameter, e.g. BindingFlags.NonPublic | BindingFlags.Instance:

Type thisType = this.GetType();
MethodInfo theMethod = thisType
    .GetMethod(TheCommandString, BindingFlags.NonPublic | BindingFlags.Instance);
theMethod.Invoke(this, userParameters);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement