views:

101

answers:

4

How can I store delegates (named, anonymous, lambda) in a generic list? Basically I am trying to build a delegate dictionary from where I can access a stored delegate using a key and execute it and return the value on demand. Is it possible to do in C# 4? Any idea to accomplish it? Note : Heterogeneous list is preferable where I can store any kind of delegates.

A: 

What about a single delegate stores all ? Multicast delegate , you can use.

saurabh
Then how can I access a particular delegate using a key? Though I don't know much about multicast delegates.
Anindya Chatterjee
+6  A: 

Does System.Collections.Generic.Dictionary<string, System.Delegate> not suffice?

Pete
that way I can't store anonymous delegates or lambdas.
Anindya Chatterjee
@Anindya Chatterjee: Yes, you can: `dic.Add("action", new Action(() => Console.WriteLine("action called!")));`
Timwi
Ya, thanks for reminding me, I totally forgot about --new Action(() => Console.WriteLine("action called!"))--
Anindya Chatterjee
A: 
        Dictionary<string, Func<int, int>> fnDict = new Dictionary<string, Func<int, int>>();
        Func<int, int> fn = (a) => a + 1;
        fnDict.Add("1", fn);
        var re = fnDict["1"](5);
Ramesh Vel
I am searching for a more generic solution where there is no constraints for the delegates.
Anindya Chatterjee
A: 

Well, here's a simple example:

class Program
{
    public delegate double MethodDelegate( double a );

    static void Main()
    {
        var delList = new List<MethodDelegate> {Foo, FooBar};


        Console.WriteLine(delList[0](12.34));
        Console.WriteLine(delList[1](16.34));

        Console.ReadLine();
    }

    private static double Foo(double a)
    {
        return Math.Round(a);
    }

    private static double FooBar(double a)
    {
        return Math.Round(a);
    }
}
TanvirK
I am not searching for this kind of solution. The solution only takes a special kind of named delegate, not others.
Anindya Chatterjee