store different generic delegates in a list in csharp

We can store different generic delegates in a list in C# by declaring a list of delegates with the specific generic signature we want to use. Here is a code example:

main.cs
using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        // Define list of delegates
        var delegates = new List<Action<int>>();

        // Add delegates to list
        delegates.Add(myInt => Console.WriteLine($"My number is {myInt}"));
        delegates.Add(myInt => Console.WriteLine($"My squared number is {myInt * myInt}"));

        // Invoke all delegates in list with the same argument
        foreach (Action<int> d in delegates)
        {
            d(5);
        }
    }
}
549 chars
22 lines

In this example, we create a list of delegates that all take an integer parameter and return void. We add two delegates to the list that each perform a different action on the integer argument they receive. We then invoke all the delegates in the list with the integer value 5.

Note that we use the Action<int> delegate type, which denotes a delegate that takes one integer parameter and returns void. If we want to use delegates with different signatures, we can create lists of delegates with other generic types such as Func<T, TResult>, which denotes a delegate that takes one parameter of type T and returns a result of type TResult.

gistlibby LogSnag