Thursday, July 20, 2017

C# Func vs Action

The difference between Func and Action is simply whether you want the delegate to return a value (use Func) or not (use Action)

Func is probably most commonly used in LINQ - for example in projections: list.Select(x => x.SomeProperty) or filtering: list.Where(x => x.SomeValue == someOtherValue) or key selection: list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)

Action is more commonly used for things like List.ForEach: execute the given action for each item in the list





Traditional way of using Delegate

//Declare delegate
public delegate void PrintMessage(string message);
public delegate int Calculate(int x, int y);


class SimpleClass
{
   public void SayHello(string name)
   {
      Console.WriteLine("Hello {0}", name);
   }


   public int Add(int x, int y)
   {
      return x+y;
   }
}

//Use delegate
var sc = new SimpleClass();
var printer = new PrintMessage(sc.SayHello);
printer("Pollux");

var calculator = new Calculate(sc.Add);
var result = calculator(5,10);



Action

This delegate was introduced in Framework 2.0. We can now use Action delegate to pass a method as a parameter without explicitly defining the delegate. The compiler will take care of it. This delegate can accept parameters but without a return type.

Action act = delegate(string name)
{
   Console.WriteLine("Hello ", name);
};


Call the delegate use act(4, 5)



Func

This was introduced in Framework3.5. This delegate is different from Action in the sense that it supports for return value.

Func fn = delegate(int x, int y)
{
   return x+y;
};


Call the delegate use Console.WriteLine(“Using Func<> :” + fn(6, 6));

No comments:

Post a Comment