In C#, a Func delegate is a built-in generic delegate type in the .NET Framework that represents a method that can take one or more input parameters and returns a value. It's commonly used for passing methods as parameters to other methods, or for defining inline expressions (like lambdas) that encapsulate code logic.
Key Points of Func Delegate
- Return Type: A Func delegate must return a value. The return type is specified by the last generic parameter.
- Input Parameters: Func can take 0 to 16 input parameters, specified by the generic type arguments. If there are no input parameters, use Func<TResult>, where TResult is the return type.
- Syntax: The Func delegate is defined as Func<T1, T2, ..., TResult>, where T1, T2, etc., are types of input parameters, and TResult is the return type.
Examples of Using Func
No Parameters (Func<TResult>):
Func<int> getRandomNumber = () => new Random().Next(1, 100);
int number = getRandomNumber(); // Calls the delegate, returns a random integer
Console.WriteLine(number);
Single Parameter (Func<T, TResult>):
Func<int, int> square = x => x * x;
int result = square(5); // Calls the delegate, returns 25
Console.WriteLine(result);
Multiple Parameters (Func<T1, T2, ..., TResult>):
Func<int, int, int> add = (x, y) => x + y;
int sum = add(3, 4); // Calls the delegate, returns 7
Console.WriteLine(sum);
How Func Delegates Are Useful
- Encapsulation of Code Logic: You can pass methods as arguments, making your code more modular.
- Lambdas with Func: Lambdas make it easy to define concise and inline methods that fit well with Func delegates.
- LINQ and Higher-Order Functions: Func is commonly used in LINQ and other functional programming constructs to operate on collections.
Comparison with Action Delegate
- Func always has a return type, while Action does not return a value (it returns void).
- Use Func when you need to return data from the delegate; use Action if no return is required.
- Example in a LINQ Query
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
Func<int, bool> isEven = x => x % 2 == 0;
var evenNumbers = numbers.Where(isEven).ToList();
Console.WriteLine(string.Join(", ", evenNumbers)); // Output: 2, 4
In this example, isEven is a Func<int, bool> delegate that filters out even numbers from the list.
No comments:
Post a Comment