views:

241

answers:

3

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>();
+13  A: 

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++);
Rohan West
If you need something a bit more flexible than a specific delegate, then try having a look at the delegate defined in the answer to this question: http://stackoverflow.com/questions/1184329/function-pointers-in-c
Matthew Scharley
A: 

It's certainly possible to create a list of a specific delegate type, like Action or Func, or any others. Since anonymous delegates can be cast to any delegate type with a compatible signature, you can create a list of delegates as long as they have compatible signatures.

I don't think creating a list of delegates with multiple kinds of signatures would be of much use, since having an unspecified signature would make it very hard to call a delegate. You should be able to do so with reflection, though. In that case you can just use a list of object.

Joren
+3  A: 

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));
Khanzor
Why is it frowned upon?
recursive
Some people think these kinds of list comprehensions should not be used with operations that have side effects. An Each method like this inherently has side effects.
Joren
@Joren: Using LINQ Expressions (including Comprehension Expressions) just for side effects is problematic, because of their lazy nature. But anonymous methods and lambda expressions are not just for LINQ, and there is no reason to restrict them to be purely functional in general. So, IMO, the use of a lambda with `List<T>.Each()` is a good approach.
Richard