Dynamically call a method in C #

I want to be able to store function references and ignore arguments until they are used.

Here is what I would like it to look like this:

StoreType f=MyFunction; ....... var r=f.Invoke(arg1,arg2,arg3) as ReturnType; 

This is similar to Action and Func, but they are strongly typed, and I want to be able to declare and use this type without knowing how many arguments and from which types the function will be executed.

How to do it in C #?

+4
source share
2 answers

For the argument count, just pass an array of the object containing the arguments.

 f.Invoke(new object[]{ arg1, args2, args3, ... }); 

For type use method

 Convert.ChangeType(objectToConvert, destinationType); 

Should work for me :)

+1
source

You can use the older delegate syntax.

public delegate ReturnType MyFunction(string arg1, int arg2, ...);

var result = MyFunction.Invoke(arg1, arg2, ...);

+1
source

All Articles