Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically call a method in C#? [duplicate]

Tags:

c#

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?

like image 782
scatman Avatar asked Jul 15 '10 10:07

scatman


3 Answers

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.

like image 83
Richard Avatar answered Sep 20 '22 05:09

Richard


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.

like image 24
Anthony Avatar answered Sep 22 '22 05:09

Anthony


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);
like image 17
Amy B Avatar answered Sep 20 '22 05:09

Amy B