I have a method:
add(int x,int y)
I also have:
int a = 5;
int b = 6;
string s = "add";
Is it possible to call add(a,b)
using the string s
?
how can i do this in c#?
Using reflection.
add
has to be a member of some type, so (cutting out a lot of detail):
typeof(MyType).GetMethod("add").Invoke(null, new [] {arg1, arg2})
This assumes add
is static (otherwise first argument to Invoke
is the object) and I don't need extra parameters to uniquely identify the method in the GetMethod
call.
Use reflection - try the Type.GetMethod
Method
Something like
MethodInfo addMethod = this.GetType().GetMethod("add");
object result = addMethod.Invoke(this, new object[] { x, y } );
You lose strong typing and compile-time checking - invoke doesn't know how many parameters the method expects, and what their types are and what the actual type of the return value is. So things could fail at runtime if you don't get it right.
It's also slower.
If the functions are known at compile time and you just want to avoid writing a switch statement.
Setup:
Dictionary<string, Func<int, int, int>> functions =
new Dictionary<string, Func<int, int, int>>();
functions["add"] = this.add;
functions["subtract"] = this.subtract;
Called by:
string functionName = "add";
int x = 1;
int y = 2;
int z = functions[functionName](x, y);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With