Difference between Action and Func in C#

Difference between Func<T> and Action<T> in C# and where to use them.

Let’s suppose we have small program which returns a number using a delegate

 
static void Main(string[] args)
{
MyCalculations del = MyCalculationsMethod;
int value = del.Invoke(5);

Console.WriteLine(“Result is: ” +value);
}
public static int MyCalculationsMethod(int num)
{
return num * num;
}

This works fine however we can use Func and Action to completely remove extra method and delegate

1) Func<> will always expect a parameter and will return a value

2) Action<> will expect a parameter but no return

Below is the code where we get rid of extra code and use Func to get our results

 static void Main(string[] args)
{
            Func<int, int> result = num => { return num * num; };
             
            Console.WriteLine(“Result is: ” + result(5));
}

Above code will do exactly the same we were doing to get calculations done – this removes all our extra code and delegate and gives us same results. This is also called Anonymous method and usually we will use it where we have a small code, may be couple of lines as we dont want to use/write anonymous methods for lengthy code and might go for old fashion i.e. a separate methods

We could use Action too but it will not reutrn a value.

Comments are closed.