views:

73

answers:

3

In c# it's possible to create a list of functions like so:

var myList = new List< Func<Foo> >();

This will allow functions (delegates) that take no arguments and return a value of type Foo to be added to the list. So something like:

Foo myFunc1() { ... }

would be a valid member of that list. My question is, how do I declare the type for a templatized function? How can I construct a List<> that will hold functions of the form:

T myFunc2<T>() { ... }
A: 

Yes this first signature is completely valid.

The signature of the last function you suggested is the following

List<Func<T>> x;

This holds a list of delegates which take no arguments and produce a T value.

JaredPar
+2  A: 

You need to do that inside a templatized class or method. Then you can refer to the generic type T just as you would refer to the specific type Foo.

In other words:

public class FuncContainer<T> 
{
    private List<Func<T>> list = new List<Func<T>>();

    public void Fill() 
    {
        // Initialize list
    }
}
driis
+1  A: 

I think the other answers so far have misunderstood the problem... and I don't think you can actually do it, if I've read it correctly. Am I right in saying you'd like to be able to write this:

List<???> list = new List<???>(); // This line won't work
list.Add(Method1);
list.Add(Method2);

...

static int Method1() { ... }
static string Method2() { ... }

If I've misunderstood, and a simple generic type parameter of T in your method or class suffices, I'll delete this answer :)

The closest you could come to the above would be something like this:

public class FuncList
{
    private readonly List<Delegate> list = new List<Delegate>();

    public void Add<T>(Func<T> func)
    {
        list.Add(func);
    }
}

You'd then use it as:

FuncList list = new FuncList();
list.Add<int>(Method1);
list.Add<string>(Method2);

Quite what you'd do with the list afterwards is tricky... what did you have in mind?

Jon Skeet