System.Generic.Delegates
Contains generic delegate types commonly used in .NET Core.
Overview
This namespace provides pre-defined generic delegate types that simplify common programming patterns, particularly those involving callbacks, event handling, and asynchronous operations. These delegates eliminate the need to create custom delegate types for many standard scenarios.
Key Delegates
System.Action
Represents an operation that accepts one or more parameters and does not return a value. The `Action` delegate family includes versions that can accept up to 16 input parameters.
public delegate void Action();
public delegate void Action(T obj);
public delegate void Action(T1 arg1, T2 arg2);
// ... and so on up to 16 parameters
Return Value: void
Used for methods that perform an action but don't return a result.
System.Func
Represents a function that takes no arguments and returns a value of a specified type. The `Func` delegate family can accept up to 16 input parameters.
public delegate TResult Func();
public delegate TResult Func(T arg);
public delegate TResult Func(T1 arg1, T2 arg2);
// ... and so on up to 16 parameters
Return Value: The type specified by TResult.
Used for methods that return a result and take no arguments.
System.Predicate
Represents a method that defines a condition based on a specified type. This is a specialized delegate for boolean-returning functions.
public delegate bool Predicate(T obj);
Return Value: bool. true if the object satisfies the condition; otherwise, false.
Used for methods that test an object for a condition and return a boolean value.
Usage Examples
Using Action<T>:
// Define a method that takes a string and prints it.
void PrintMessage(string message)
{
Console.WriteLine($"Message: {message}");
}
// Create an Action delegate pointing to the PrintMessage method.
Action<string> printAction = PrintMessage;
// Invoke the delegate.
printAction("Hello, Delegates!");
Using Func<T, TResult>:
// Define a method that takes an integer and returns its square.
int Square(int number)
{
return number * number;
}
// Create a Func delegate pointing to the Square method.
Func<int, int> squareFunc = Square;
// Invoke the delegate.
int result = squareFunc(5); // result will be 25
Console.WriteLine($"The square of 5 is: {result}");
Using Predicate<T>:
// Define a method that checks if a number is even.
bool IsEven(int number)
{
return number % 2 == 0;
}
// Create a Predicate delegate pointing to the IsEven method.
Predicate<int> isEvenPredicate = IsEven;
// Use the predicate.
bool check1 = isEvenPredicate(10); // check1 will be true
bool check2 = isEvenPredicate(7); // check2 will be false
Console.WriteLine($"Is 10 even? {check1}, Is 7 even? {check2}");