store generic delegates in a list in csharp

To store a generic delegate in a list in C#, you can use the System.Action or System.Func classes which are built-in delegate types in C#.

The System.Action delegate represents a method that takes no parameters and returns void. Whereas System.Func is a delegate type that can represent a method that takes up to 16 input parameters and returns a value.

Here's an example of how you can store a generic delegate in a list using lambda expressions:

main.cs
// Sample Delegate
private delegate void MyDelegate(int x);

// Create a list of generic action delegates
List<Action<int>> actions = new List<Action<int>>();

// Add delegates to the list
actions.Add((x) => Console.WriteLine($"Delegate 1: x = {x}"));
actions.Add((x) => Console.WriteLine($"Delegate 2: x * 2 = {x * 2}"));

// Invoke each delegate in the list with 10 as the input parameter
foreach (var action in actions)
{
    action(10);
}
443 chars
16 lines

In the example above, we have created a generic list of Action<int> delegates that can take an integer input parameter and return void. We have then added two delegates to the list using lambda expressions that print the value of x and x * 2 respectively. Finally, we invoke each delegate in the list with 10 as the input parameter using a foreach loop. This will output:

main.cs
Delegate 1: x = 10
Delegate 2: x * 2 = 20
42 chars
3 lines

gistlibby LogSnag