Sobes.tech
Junior

What is the difference between Action and Func delegates in C#?

sobes.tech AI

Answer from AI

The main difference between Action and Func lies in their return values:

  • Action: A delegate that takes from 0 to 16 parameters but does not return any value (returns void).
  • Func: A delegate that takes from 0 to 16 input parameters and returns a value of the specified type. The return type is indicated in the last parameter <TResult>.

Examples:

// Example of using Action
Action<string> printMessage = (message) =>
{
    Console.WriteLine(message);
};
printMessage("Hello, world!");
// Example of using Func
Func<int, int, int> sum = (a, b) => a + b;
int result = sum(5, 3); // result will be 8
Console.WriteLine($"Sum: {result}");