How to store delegates in a List

32,098

Solution 1

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

Solution 2

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);
    }
}

Solution 3

    public delegate void DoSomething();

    static void Main(string[] args)
    {
        List<DoSomething> lstOfDelegate = new List<DoSomething>();
        int iCnt = 0;
        while (iCnt < 10)
        {
            lstOfDelegate.Add(delegate { Console.WriteLine(iCnt); });
            iCnt++;
        }

        foreach (var item in lstOfDelegate)
        {
            item.Invoke();
        }
        Console.ReadLine();
    }
Share:
32,098
Anindya Chatterjee
Author by

Anindya Chatterjee

I supposed to know something about Computer and its science, but the reality is I know nothing !!!

Updated on July 09, 2022

Comments

  • Anindya Chatterjee
    Anindya Chatterjee almost 2 years

    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.

  • Anindya Chatterjee
    Anindya Chatterjee over 13 years
    that way I can't store anonymous delegates or lambdas.
  • ssss
    ssss over 13 years
    @Anindya Chatterjee: Yes, you can: dic.Add("action", new Action(() => Console.WriteLine("action called!")));
  • Anindya Chatterjee
    Anindya Chatterjee over 13 years
    I am not searching for this kind of solution. The solution only takes a special kind of named delegate, not others.
  • Anindya Chatterjee
    Anindya Chatterjee over 13 years
    I am searching for a more generic solution where there is no constraints for the delegates.
  • Anindya Chatterjee
    Anindya Chatterjee over 13 years
    Ya, thanks for reminding me, I totally forgot about --new Action(() => Console.WriteLine("action called!"))--