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, and Predicate are built-in delegates so you don’t have to define custom delegate types.
TypePurposeReturnsParameters
FuncRepresents a method that returns a valueYes0 or more input parameters
ActionRepresents a method that does not return a valueNo0 or more input parameters
PredicateRepresents a method that returns a boolbool1 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?

  1. Simplifies code: no need to define custom delegates.

  2. Works well with LINQ and functional patterns.

  3. 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 TypeReturn TypeParametersExample Usage
Func<T>T0+ paramsFunc<int,int,int> add
Action<T>void0+ paramsAction<string> greet
Predicate<T>bool1 paramPredicate<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?