In this post, we will explore the variance between Func delegate and Action delegate in C#. Before delving into the disparities, let's grasp the meaning of each concept. Functions characterized by particular signatures are denoted by a construct known as delegate in the C# language.
What is a Delegate?
A delegate is a data type that enables the invocation of another method with a similar signature, particularly when the method is unknown at the time of coding. The keyword "delegate" is utilized to establish delegates, essentially functioning as callback functions. Delegates can be either predefined or enclosed within a class. The key contrast lies in the former being applicable to delegates that yield a result, whereas the latter is designed for those without return values. Utilizing delegates, programs can implement callback functions, manage events, and handle tasks where executing a method at a later stage is required. In C#, delegates are supported in diverse formats, with Action and Func being the most prevalent ones located in the System namespace.
What is Action Delegate in C#?
The Action Delegate serves as a formal delegate within the system, designed as a generic delegate type. By utilizing this delegate, it establishes a standardized approach for defining generic delegates instead of creating custom ones, ultimately enhancing code readability and efficiency. This delegate is located within the System namespace and is capable of accepting a single parameter at minimum and up to sixteen parameters at maximum. Typically, the primary purpose of the Action delegate is to be passed into methods that do not necessitate a return value. Essentially, it is employed with methods that have a void return type. Additionally, the Action delegate can accommodate the same type of parameters or a variety of parameter types.
Syntax:
It has the following syntax:
public delegate void Action < in Param1, in Param2 >(Param1 arg1, Param2 arg2);
Here, Param1 and Param2 represent restrictions on the input parameters, while arg1 and arg2 serve as formal parameters within the method, encapsulated by an Action delegate. This delegate type, Action, is predefined to accommodate methods that accept any number of arguments and do not return any output value.
Example:
Let's consider a scenario to demonstrate the action delegate in C#.
using System;
class ActionDelegate{
// Method
public static void paramFun(int p1, int q1)
{
Console.WriteLine(p1 - q1);
}
// Main method
static public void Main()
{
//the action delegate with 2 parameters
Action<int, int> value = paramFun;
value(28, 5);
}
}
Output:
Explanation:
In the preceding code snippet, we wrap the action delegate to enhance the program's clarity and minimize the code length. Within this context, the 'action' delegate encompasses 'error' and 'completion' as its parameters. Ultimately, the Action delegate executes the paramFun function by means of the method directly allocated to it.
What is the Func Delegate in C#?
Func represents a unique delegate within the System namespace, frequently employed in C#. This delegate acts as a flexible mechanism for specifying functions that can accept a single input parameter or, in scenarios where no parameters are required, can produce a result. Leveraging Func eliminates the necessity of creating a bespoke delegate, streamlining the development process and boosting productivity.
Named appropriately, Func is specifically designed for functions that yield a result, making it an ideal delegate to encapsulate such functions. This feature enhances the development process and encourages the creation of more organized and succinct code. Since Func is a versatile delegate with generic functionality, it is part of the system namespace. It can accommodate anywhere from 0 to a maximum of 16 parameters, with the provision for a single output parameter. The final parameter of a Func delegate signifies the return type, reflecting the expected outcome. This can be the same type as the input parameters or a different type altogether.
Syntax:
It has the following syntax.
namespace System
{
public delegate TRes Func<in Temp, out TRes>(Temp arg);
}
Example:
Let's consider a scenario to demonstrate the Func delegate in C#.
using System;
class FuncDelegate{
//the declaration of the delegate
public delegate int fun_delegate(int s1, int d1, int f1, int g1);
// Method
public static int delegatemethod(int s1, int d1,
int f1, int g1)
{
return s1 * d1 * f1 * g1;
}
// Main method
static public void Main()
{
// object creation for fun_delegate
fun_delegate obj = delegatemethod;
Console.WriteLine(obj(19, 39, 32, 36));
}
}
Output:
853632
Explanation:
Within the FuncDelegate class, a delegate named fundelegate is defined using the delegate keyword. This delegate is characterized by a method signature that accepts four integer parameters and outputs an integer value. Following this, the method delegatemethod is established within a static type. This approach involves comparing the specification of fundelegate with its statically defined signature. It involves aggregating the values of the four input integers s1, d1, f1, and g1 to produce a final outcome.
In the Main function, an instance named obj is instantiated based on the fun_delegate interface and then provided with the delegatemethod function. This results in obj executing the delegate method directly or executing the delegatemethod function.
Finally, the obj delegate is called with four integer parameters: 19, 39, 32, and 36, denoted as obj(19, 39, 32, 36). The result is displayed on the console using the Console.WriteLine function.
Key difference between Func delegate and Action delegate
The <style> section includes a diagram with a dark background color, a border radius of 12 pixels, padding of 40 pixels, margin of 20 pixels on the top and bottom, and centered text alignment. Within this diagram, there is an icon with a font size of 3rem and a margin bottom of 10 pixels. The text inside the diagram is styled with a color of #9ca3af and a font size of 1rem. This design is essential for enhancing the visual representation of information in a structured and organized manner.
Here are the variances between Func delegate and Action delegate in C#:
- Func delegate can return a value, while Action delegate cannot return a value.
- Func delegate must specify the return type, whereas Action delegate does not have a return type.
- Func delegate can take up to 16 input parameters, while Action delegate can take up to 16 input parameters but does not return a value.
- Func delegate is suitable for methods that return a value, whereas Action delegate is suitable for methods that perform an action but do not return a value.
| Function | Func | Action |
|---|---|---|
| Return type | It has the return type. | No return type. |
| Number of parameters | It can have multiple input parameters. | Mostly for methods with input parameters. |
| Number of type parameters | The return type can have one or more, but the input parameter can have more than one. | At least one for each measuring parameter. |
| Usage | It is for ways having values return. | Acceptable means of return value. |
| Delegate signature | Func | Action |
| Example | Func | Action |
| Error handling | Use methods for encapsulation. | Use methods for encapsulation and side effects |
Conclusion:
In summary, both Func delegates and Action delegates within C# share a common trait of encapsulating specific method signatures into a unified entity. The selection of the method solely depends on the nature of the operation (whether it yields a result or not), which is then utilized for specific functionalities. Func serves as a functional form utilized when an output is anticipated, thereby enabling a broader range of options for processing diverse data types. Conversely, Action is suitable for scenarios where the function executed does not return a value, making it ideal for handling side effects or methods that return void. Therefore, by comprehending the distinctions between the two, programmers can appropriately choose the relevant delegate based on their requirements, fostering more organized and easily understandable code.