C# `Func` vs. `Action` Delegates: Understanding Their Differences and Applications

Learn the key distinctions between `Func` and `Action` delegates in C#. This tutorial explains their signatures (parameters and return types), demonstrates their usage in representing methods with and without return values, and highlights their applications in callbacks, event handling, and asynchronous operations.



`Func` vs. `Action` Delegates in C#

In C#, `Func` and `Action` are predefined generic delegates used to represent methods with specific signatures. They are extremely useful for passing methods as parameters, enabling callback mechanisms and improving code organization. The key difference lies in their return types: `Func` delegates return a value, while `Action` delegates do not.

Understanding Delegates in C#

A delegate is a type that holds a reference to a method. It defines a method's signature (parameters and return type). You can then assign a method to a delegate instance and invoke the method through the delegate. Delegates provide a powerful way to handle callbacks and events.

The `Action` Delegate

The `Action` delegate is a predefined generic delegate that represents methods with no return value (`void`). It can take zero to sixteen input parameters of various types.

Syntax


public delegate void Action<in T1, in T2, ...>(T1 arg1, T2 arg2, ...);

Example


Action<int, int> myAction = (x, y) => Console.WriteLine(x + y);
myAction(5, 3); // Output: 8

The `Func` Delegate

The `Func` delegate is a predefined generic delegate that represents methods that return a value. It can take zero to sixteen input parameters and returns a single value. The last type parameter in the `Func` delegate definition represents the return type.

Syntax


public delegate TResult Func<in T1, in T2, ..., TResult>(T1 arg1, T2 arg2, ...);

Example


Func<int, int, int> add = (x, y) => x + y;
int sum = add(7, 3); // sum will be 10
Console.WriteLine(sum);

Key Differences: `Action` vs. `Func`

Feature `Action` `Func`
Return Type `void` (no return value) TResult (returns a value)
Parameters 0 to 16 input parameters 0 to 16 input parameters, plus one output parameter (return type)
Typical Use Methods that perform actions (e.g., event handlers) Methods that compute and return a value