Delegates
In C#, delegates are types that represent references to methods. They can be used to define callback methods, event handlers, and can also be used in functional programming patterns. Below is a list of commonly used delegates in C#, including built-in delegates and custom delegates.
Built-in Delegates
Action: Represents a delegate that can point to a method that does not return a value. It can take up to 16 parameters.- Examples:
Action(no parameters)Action<T>(one parameter)Action<T1, T2>(two parameters)Action<T1, T2, T3>(three parameters)- ...
Action<T1, T2, ..., T16>(up to 16 parameters)
- Examples:
Func: Represents a delegate that can point to a method that returns a value. It can also take up to 16 parameters.- Examples:
Func<TResult>(no parameters)Func<T1, TResult>(one parameter)Func<T1, T2, TResult>(two parameters)Func<T1, T2, T3, TResult>(three parameters)- ...
Func<T1, T2, ..., T16, TResult>(up to 16 parameters)
- Examples:
Predicate: Represents a delegate that takes one input parameter and returns a boolean value. It is commonly used for filtering data.- Example:
Predicate<T>(one parameter)
- Example:
Custom Delegates
In addition to the built-in delegates, you can also create custom delegates for specific use cases.
Simple Custom Delegate: A delegate that matches the signature of a method you want to reference.
Delegate with Parameters and Return Value: You can define a delegate that returns a value.
Example Usage of Delegates
Here's a complete example demonstrating the use of built-in and custom delegates:
Summary
- Built-in Delegates:
Action,Func, andPredicateare commonly used in C# for callbacks and functional programming. - Custom Delegates: You can create your own delegate types for specific method signatures.
- Flexibility: Delegates provide a way to reference methods and can be used for events, callbacks, and functional programming styles.
By understanding and utilizing delegates effectively, you can create more modular, reusable, and maintainable code in C#.
Comments
Post a Comment