Built-in Delegate Types
Explore the use of built-in delegate types in C# including Action, Func, Predicate, and EventHandler. Understand how these generic delegates reduce boilerplate code and improve readability while enabling flexible method signatures and event handling in your .NET applications.
We'll cover the following...
In the previous lessons, we declared custom delegate types like MessagePrinter and GoalScoredHandler to define specific method signatures. While this approach works, creating a new delegate definition for every unique signature creates unnecessary boilerplate code.
To simplify this, the .NET platform provides a set of built-in generic delegates—Action, Func, Predicate, and EventHandler—that cover the vast majority of use cases. By using these types, we can write concise and readable code without cluttering our namespaces with custom delegate definitions.
The Action delegate
Defining custom delegate types for every situation is often unnecessary because the .NET platform provides built-in generic delegates. The Action delegate represents a method that takes parameters and returns void.
It is defined as follows:
public delegate void Action<T>(T parameter);
We see that Action accepts a generic parameter T and returns void. We can instantiate it directly without ...