Is it possible to create a list of anonymous delegates in C#? Here is code I would love to write but it doesn't compile:
Action<int> method;
List<method> operations = new List<method>();
You can write this, for example
Action<int> method = j => j++;
List<Action<int>> operations = new List<Action<int>>();
operations.Add(method);
operations.Add(i => i++);
The problem with your code is that you are trying to specify an instance as a type argument to List.
Action<int> method
is an instance, whereas Action<int>
is a type.
As another poster mentions, you just need to declare the type of list as Action<int>
, that is, with just the type parameter.
e.g.
var myNum = 5;
var myops = new List<Action<int>>();
myops.Add(j => j++);
myops.Add(j => j++);
foreach(var method in myops)
{
Console.WriteLine(method(myNum));
}
// Frowned upon, but fun syntax
myops.Each(method => method(myNum));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With