Letβs go through Func
, Action
, and Predicate
in C#, which are predefined generic delegates and make working with delegates much easier.
π 1. What Are They?
Func
,Action
, andPredicate
are built-in delegates so you donβt have to define custom delegate types.
Type | Purpose | Returns | Parameters |
---|---|---|---|
Func | Represents a method that returns a value | Yes | 0 or more input parameters |
Action | Represents a method that does not return a value | No | 0 or more input parameters |
Predicate | Represents a method that returns a bool | bool | 1 input parameter |
π 2. Func
Example
-
Syntax:
Func<T1, T2, ..., TResult>
-
Last type parameter is the return type.
class Program
{
static void Main()
{
Func<int, int, int> add = (x, y) => x + y;
int result = add(5, 7);
Console.WriteLine(result); // 12
}
}
Func<int,int,int>
β takes two ints, returns int.
π 3. Action
Example
-
Syntax:
Action<T1, T2, ...>
-
Always void return type.
class Program
{
static void Main()
{
Action<string> greet = name => Console.WriteLine($"Hello, {name}!");
greet("Alice"); // Output: Hello, Alice!
}
}
Action<string>
β takes one string, returns void.
π 4. Predicate
Example
-
Syntax:
Predicate<T>
-
Always returns bool and takes one parameter.
class Program
{
static void Main()
{
Predicate<int> isEven = x => x % 2 == 0;
Console.WriteLine(isEven(4)); // True
Console.WriteLine(isEven(5)); // False
}
}
Predicate<int>
β takes int, returns bool.
π 5. Why Use These?
-
Simplifies code: no need to define custom delegates.
-
Works well with LINQ and functional patterns.
-
Type-safe and concise with lambdas.
Example with LINQ:
List<int> numbers = new() { 1, 2, 3, 4, 5 };
Predicate<int> isEven = x => x % 2 == 0;
List<int> evens = numbers.FindAll(isEven);
Console.WriteLine(string.Join(", ", evens)); // 2, 4
π 6. Quick Reference
Delegate Type | Return Type | Parameters | Example Usage |
---|---|---|---|
Func<T> | T | 0+ params | Func<int,int,int> add |
Action<T> | void | 0+ params | Action<string> greet |
Predicate<T> | bool | 1 param | Predicate<int> isEven |
β Summary:
-
Func
β returns a value, can have multiple parameters. -
Action
β returns void, can have multiple parameters. -
Predicate
β returns bool, takes one parameter. -
These built-in delegates simplify passing methods as parameters.
If you want, I can also make a visual diagram showing Func vs Action vs Predicate with arrows for parameters and return types β it makes it super easy to remember.
Do you want me to make that diagram?