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!
You need to cast the
objectin the list to aBinaryOp, or, better, use a more specific type parameter for the list: