Alex Rivera | Logout

How to dynamically call a method in C#?

Asked 2010-07-15T10:49:37.227
41

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?

c#
Edit
Report

1 Answer

78

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.

answered 2010-07-15T10:54:29.763

Your Answer