C# Func vs. Action? What is the difference between a Func
The main difference is whether one wants the delegate to return a value or not. By using Func it will expect the delegate to return a value and Action for no value (void)
1. Func for methods that return value eg. int Calculate(), performs an operation on the generic argument(s) and returns a value.
2. Action for methods that do not return value e.g void ProcessData(), performs an operation on the generic arguments.
In Linq you see a lot of Func that are being used.
Example in flitering
1 2 3 4 |
//filtering var person = Persons.Where(x => x.Name == "john"); //select var user = Persons.Select(x => x.Name); |
For Action one will see it in Linq ForEach statement
1 2 3 4 5 6 7 8 9 |
Persons.ForEach(x => x.Name.UpperCase()); //define an Action with output string to console Action<string> printString = x => Console.WriteLine(x); //now you can pass the action/delegate to other methods void Process(Action<string> printAction) { printAction("hello");} //one can call the method as in Process(printString); |
Leave A Comment