C# – use a List 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)

Any ideas on how to accomplish this?

Best Solution

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>();


foreach(BinaryOp method in methodsToExecute)