Syntax help: calling a delegate from a dictionary

If I have a dictionary where the values are delegates (for example, lets say the delegates return void and take two int arguments), what is the correct syntax to call/invoke a delegate once it's retrieved via a key. This is essentially a function dispatch mechanism, but I'm too new to C# to know the calling details. Thanks.



Answer this question

Syntax help: calling a delegate from a dictionary

  • Michael Tallhamer

    Assuming you’ve got something like this already:

    public delegate void Delegate1(int x);

    public delegate void Delegate2(string s);

    public delegate int Delegate3();

    public void Func1(int x)

    {

    Console.WriteLine("Func1 called");

    }

    public void Func2(string s)

    {

    Console.WriteLine("Func2 called");

    }

    public int Func3()

    {

    Console.WriteLine("Func3 called");

    return 0;

    }

    And your Dictionary is strongly typed and you’ve already populated it similar to this:

    Dictionary<string, Delegate> dict = new Dictionary<string, Delegate>();

    dict.Add("Func1", new Delegate1(Func1));

    dict.Add("Func2", new Delegate2(Func2));

    dict.Add("Func3", new Delegate3(Func3));

    The easiest way to invoke the various delegates is to index them by name and call DynamicInvoke() and pass in the needed parameters required by the delegate ala:

    dict["Func1"].DynamicInvoke(new object[] { 4 });

    dict["Func2"].DynamicInvoke(new object[] { "Hello" });

    dict["Func3"].DynamicInvoke(null);

    Does this answer your question



  • Syntax help: calling a delegate from a dictionary