Calling a function from a string in C#
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);
You can invoke methods of a class instance using reflection, doing a dynamic method invocation:
Suppose that you have a method called hello in a the actual instance (this):
string methodName = "hello";
//Get the method information using the method info class
MethodInfo mi = this.GetType().GetMethod(methodName);
//Invoke the method
// (null- no parameter for the method call
// or you can pass the array of parameters...)
mi.Invoke(this, null);