X

C# Func vs. Action

dotnet C#

C# Func vs. Action? What is the difference between a Func vs an Action in C#?

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

  //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

  
  Persons.ForEach(x => x.Name.UpperCase());
  //define an Action with output string to console
  Action printString = x => Console.WriteLine(x);

  //now you can pass the action/delegate to other methods
  void Process(Action printAction) {  printAction("hello");}

  //one can call the method as in
  Process(printString);
Categories: .NET C#
Tags: .netC#csharp
Taswar Bhatti:
Related Post