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 expressions to them. The main difference is that an Action does not have a return value, and a Func does. So, let's 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,  we can do it via action.

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, and each of those is expecting 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 it by passing an input integer parameter like this.

act(3);

Running this into a console application project, we’ll see something like the following.

(Add some lines to add labels).

Add Labels

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.

Func<int, int> 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 because of the output parameter.

After that, we are going to use a Console.WriteLine calls our function to print the result on the console.

Console.WriteLine(func(4));

It is going to give us the next result on the screen.

Result

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

Happy coding!


Similar Articles