Action And Func Delegates In C#

Action and Func are similar things, but they are slightly different. Both of them are generic delegates, which means that you can assign both anonymous methods and lambda expression to them. The main difference is that an Action does not have a return value and a Func does. So lets write a simple example.

Since there is nothing to be returned and we really just want to execute it and not have anything to come back, so the way we can do it is via an Action.

  1. Action<int> act = num => { Console.WriteLine("Executing the action : {0} * 2 = {1}", num, num * 2); };  
As you can see as you type the Action class, there are sixteen overloads in there, each of those are expecting for a generic type parameter that you can pass into the action. Sixteen is to how many parameters an Action can take in the current version of C#.

In our case we used one single parameter, this is enough for our example. We assigned the lambda expression within a Console. Write a function to print it out in the console, so we can easily use that by passing an input integer parameter like this.
  1. act(3);  
Running this into a console application project we’ll see something like the following:

(Add some line to add labels)

action

Then in the other example we will use a Func to return a value.

A Func is a generic delegate type that allows you to return a value of whatever type parameter you pass at the end. In case you pass only one parameter it will take it as the output parameter.
  1. Func<intint> func = num => { return num * 2; };  
In the above line the compiler is going to assume that the first type parameter is the input parameter and the second type parameter is the output parameter. Functions take seventeen overloads, this is because of the output parameter.

After that we are going to use a Console.WriteLine calling our function to print the result on the console.
  1. Console.WriteLine(func(4));  
It is going to give us the next result in the screen.

Func

These are two simple ways that show how to use these generic delegates in c#, they can be very useful and without doubt they are definitely cool things that you can play around with to make your code way more extensible. So I hope it could be helpful for you.

Happy coding!