Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a List<T> as a collection of method pointers? (C#)

I want to create a list of methods to execute. Each method has the same signature. I thought about putting delegates in a generic collection, but I keep getting this error:

'method' is a 'variable' but is used like a 'method'

In theory, here is what I would like to do:

List<object> methodsToExecute;

int Add(int x, int y)
{ return x+y; }

int Subtract(int x, int y)
{ return x-y; }

delegate int BinaryOp(int x, int y);

methodsToExecute.add(new BinaryOp(add));
methodsToExecute.add(new BinaryOp(subtract));

foreach(object method in methodsToExecute)
{
    method(1,2);
}

Any ideas on how to accomplish this? Thanks!

like image 804
Bret Walker Avatar asked Sep 25 '08 19:09

Bret Walker


2 Answers

You need to cast the object in the list to a BinaryOp, or, better, use a more specific type parameter for the list:

delegate int BinaryOp(int x, int y);

List<BinaryOp> methodsToExecute = new List<BinaryOp>();

methodsToExecute.add(Add);
methodsToExecute.add(Subtract);

foreach(BinaryOp method in methodsToExecute)
{
    method(1,2);
}
like image 150
Khoth Avatar answered Sep 22 '22 02:09

Khoth


Using .NET 3.0 (or 3.5?) you have generic delegates.

Try this:

List<Func<int, int, int>> methodsToExecute = new List<Func<int, int, int>>();

methodsToExecute.Add(Subtract);

methodsToExecute.Add[0](1,2); // equivalent to Subtract(1,2)
like image 38
David Alpert Avatar answered Sep 23 '22 02:09

David Alpert