store different generic delegates in a list without dynamicinvoke in csharp

In C#, you can store different types of generic delegates in a List using the Action and Func classes.

The Action class represents a delegate that does not return a value and can take up to 16 input parameters. The Func class, on the other hand, represents a delegate that returns a value and can take up to 16 input parameters.

Here's an example of how to store different types of generic delegates in a List using Action and Func:

main.cs
List<Delegate> delegates = new List<Delegate>();

Action<string> del1 = (s) => Console.WriteLine(s);
Func<int, int, int> del2 = (a, b) => a + b;
Action<int, string> del3 = (i, s) => Console.WriteLine($"Number {i}, String {s}");

delegates.Add(del1);
delegates.Add(del2);
delegates.Add(del3);

foreach (Delegate del in delegates)
{
    if (del is Action<string>)
    {
        ((Action<string>)del)("Hello World");
    }
    else if (del is Func<int, int, int>)
    {
        int result = ((Func<int, int, int>)del)(1, 2);
        Console.WriteLine(result);
    }
    else if (del is Action<int, string>)
    {
        ((Action<int, string>)del)(42, "foo");
    }
}
665 chars
27 lines

In this example, we create three different generic delegates: del1 of type Action<string>, del2 of type Func<int, int, int>, and del3 of type Action<int, string>. We then add these delegates to a List called delegates.

To invoke the delegates in the List, we loop through each delegate and use the is operator to determine its type. We then cast the delegate to its appropriate type and invoke it accordingly.

Note that this method does not use DynamicInvoke, which is useful for performance reasons as it avoids the overhead of invoking delegates using a reflection-based mechanism.

gistlibby LogSnag