Action And Func Delegates In C#

Introduction

In this article, we are going to learn about the Action and Func delegates in C# but before that will look at What is Delegate first.

Topics to be Covered,

  1. What is Delegate
  2. Action Delegate
  3. Func Delegate

What is a Delegate?

A delegate is a type-safe function pointer that can be used to refer to another method with the same signature as the delegate. The "delegate" keyword is used to declare delegates, which are used to define callback methods and provide event handling. A delegate can be declared as a standalone object or nested within a class.

The primary distinction between Func and Action delegates is that the former is used for delegates that return a value, whereas the latter can be used for delegates that have no return value.

Action Delegate

A built-in generic type delegate is the action delegate. This delegate eliminates the need to define a custom delegate, as illustrated in the examples below, and improves the readability and optimization of your application. It's found in the System namespace.

It can have a minimum of 1 and a maximum of 16 input parameters, but no output parameters. The Action delegate is typically used with methods that have no return value, or methods with a void return type. It can also have parameters of the same kind as well as parameters of other types.

Let us define one method which will have 3 input parameters and returns the added value.

Program.cs 

static void AddNums2(int x, float y, double z) 
{ 
    Console.WriteLine(x + y + z); 
}
static void Main() 
{ 
    Action<int,float,double> action = AddNums2; 
    action.Invoke(100, 45.6f, 165.986); 
}

Func Delegate

A Func is a generic type delegate that comes with the language. This delegate eliminates the need to define a custom delegate as demonstrated in the preceding example, making your program more understandable and efficient. Because Func is a generic delegate, it is found in the System namespace.

It can have a minimum of 0 and a maximum of 16 input parameters, but only one output parameter. The out argument, which is a return type and is used for the result, is the last parameter of the Func delegate.

static double AddNums1(int x, float y, double z) 
{ 
    return x + y + z; 
}
static void Main() 
{ 
    Func<int,float,double,double> func = AddNums1; 
    double result = func.Invoke(100, 34.5f, 193.667); 
    Console.WriteLine(result); 
}

Let's run the application and see the output in the console window

Delegates in C#

Conclusion

The above article demonstrates a detailed overview of the Action and Func Delegates and how to use make use of it with all the options available in C#.

Keep Learning!