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

In C#, Action and Func are two different types of delegates, distinguished by their differences in parameters and return values.

  1. Action is a delegate type in C# that does not return a value. It can take up to 16 input parameters but does not have a return value. For example, an Action delegate can represent a method with no parameters or a method with multiple parameters but no return value.

Original: 我们需要尽快完成这项任务。
Paraphrased: We need to finish this task as soon as possible.

Action<int, string> action = (x, y) => Console.WriteLine($"Action: {x}, {y}");
action(10, "Hello");

The Action delegate here takes an int parameter and a string parameter, and then prints them to the console.

  1. Func is a delegate type that has a return value. It can accept up to 16 input parameters and return a single value. For example, a Func delegate can represent a method with no parameters that returns an integer, or a method with multiple parameters that returns a string.

Original: 我在学校遇到了我的朋友。
Paraphrased: I met my friend at school.

Func<int, int, string> func = (x, y) => $"Func: {x + y}";
string result = func(10, 20);
Console.WriteLine(result);

The ‘Func’ delegate here takes two parameters of type int, and then returns their sum as a result of type string.

In summary, both Action and Func are delegate types used to represent references to methods. The main difference between them is that Action does not have a return value, while Func does have a return value.

bannerAds