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.cs443 chars16 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.cs42 chars3 lines
gistlibby LogSnag