Could you explain the difference between Func vs. Action vs. Predicate?

Here’s an explanation of the differences between Func, Action, and Predicate in C#:

  1. Func:
    • Func is a generic delegate type in C# that represents a method with a return value.
    • It can have zero or more input parameters and a return type specified as generic type arguments.
    • The last type argument represents the return type, while the preceding type arguments represent the input parameter types.
    • Examples: Func<int> (no input parameters, returns an int), Func<int, string> (takes an int parameter, returns a string).
  2. Action:
    • Action is a generic delegate type in C# that represents a method with no return value (i.e., void return type).
    • It can have zero or more input parameters specified as generic type arguments.
    • The type arguments represent the input parameter types, and there is no type argument for the return value (since it is void).
    • Examples: Action (no input parameters, no return value), Action<int, string> (takes an int and a string parameter, no return value).
  3. Predicate:
    • Predicate is a generic delegate type in C# that represents a method that takes a single parameter and returns a Boolean value.
    • It is commonly used for testing conditions and checking if an item satisfies a specific criteria.
    • It has one generic type argument that represents the type of the parameter being tested.
    • Examples: Predicate<int> (takes an int parameter, returns a bool), Predicate<string> (takes a string parameter, returns a bool).

In summary:

  • Func represents a method with a return value and can have zero or more input parameters.
  • Action represents a method with no return value (void) and can have zero or more input parameters.
  • Predicate represents a method that takes a single parameter and returns a Boolean value.

These delegate types provide a convenient way to define and pass methods as parameters or store them as variables. Func and Action are often used for general-purpose delegates, while Predicate is specifically designed for testing conditions.

error: Content is protected !!