Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a list of dynamic functions and dynamically calling them

Tags:

I would like to be able to store various static methods in a List and later look them up and dynamically call them.

Each of the static methods has different numbers of args, types and return values

static int X(int,int)....
static string Y(int,int,string) 

I'd like to have a List that I can add them all to:

List<dynamic> list

list.Add(X);
list.Add(Y);

and later:

dynamic result = list[0](1,2);
dynamic result2 = list[1](5,10,"hello")

How to do this in C# 4?

like image 395
freddy smith Avatar asked Nov 16 '11 13:11

freddy smith


2 Answers

You can create a list of delegate-instances, using an appropriate delegate-type for each method.

var list = new List<dynamic>
          {
               new Func<int, int, int> (X),
               new Func<int, int, string, string> (Y)
          };

dynamic result = list[0](1, 2); // like X(1, 2)
dynamic result2 = list[1](5, 10, "hello") // like Y(5, 10, "hello")
like image 199
Ani Avatar answered Oct 20 '22 00:10

Ani


You actually don't need the power of dynamic here, you can do with simple List<object>:

class Program
{
    static int f(int x) { return x + 1; }
    static void g(int x, int y) { Console.WriteLine("hallo"); }
    static void Main(string[] args)
    {
        List<object> l = new List<object>();
        l.Add((Func<int, int>)f);
        l.Add((Action<int, int>)g);
        int r = ((Func<int, int>)l[0])(5);
        ((Action<int, int>)l[1])(0, 0);
    }
}

(well, you need a cast, but you need to somehow know the signature of each of the stored methods anyway)

like image 22
Vlad Avatar answered Oct 20 '22 00:10

Vlad