Is List <T> where T is an anonymous delegate?
Is it possible to create a list of anonymous delegates in C #? Here is the code I would like to write, but it does not 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, while Action<int> is a type.
As another poster is mentioned, you just need to declare the list type as Action<int> , i.e. only with the type parameter.
eg.
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)); Of course, it is possible to create a list of a specific type of delegate, such as Action or Func, or any other. Because anonymous delegates can be transferred to any type of delegate with a compatible signature, you can create a list of delegates if they have compatible signatures.
I do not think that creating a list of delegates with several types of signatures will be very useful, since having an unspecified signature will make it difficult to call a delegate. However, you should be able to do this with reflection. In this case, you can simply use the list of objects.