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
2010-09-28 13:39:59
Then how can I access a particular delegate using a key? Though I don't know much about multicast delegates.
Anindya Chatterjee
2010-09-28 13:41:09
+6
A:
Does System.Collections.Generic.Dictionary<string, System.Delegate>
not suffice?
Pete
2010-09-28 13:42:08
@Anindya Chatterjee: Yes, you can: `dic.Add("action", new Action(() => Console.WriteLine("action called!")));`
Timwi
2010-09-28 13:45:30
Ya, thanks for reminding me, I totally forgot about --new Action(() => Console.WriteLine("action called!"))--
Anindya Chatterjee
2010-09-28 13:56:27
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
2010-09-28 13:47:21
I am searching for a more generic solution where there is no constraints for the delegates.
Anindya Chatterjee
2010-09-28 13:53:51
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
2010-09-28 13:49:47
I am not searching for this kind of solution. The solution only takes a special kind of named delegate, not others.
Anindya Chatterjee
2010-09-28 13:52:27