In c#, Action is a built-in generic delegate same as Func delegate to hold the reference of one or more methods, but the only difference is the Action delegate will not return any value.
In previous chapters, we learned about delegates and will be used as shown following to hold the reference of methods with the same signature.
If you observe the above example, we created a delegate object called “SampleDelegate” to hold the reference of Add & Subtract methods.
When we execute the above example, we will get the result as shown below.
To avoid the declaration of custom delegate object (SampleDelegate), as we defined in the above example, the generic built-in delegates such as Func, Action, Predicate have been introduced in C# 3.0.
From C# 3.0 onwards, the Action delegate will available automatically with the System namespace, and it will accept zero or more (16) input parameters and does not return a value.
Following is the syntax of declaring an Action delegate with one input parameter in c#.
Here, the parameters in the angle bracket < >
will be considered as input parameters and void
is the return type.
If we want to create an Action delegate with two input parameters, that would be as shown below.
Like this, an Action delegate can include 0 to 16 input parameters of different types based on our requirements.
Following is the example of defining the Action delegate to hold the reference of one or more methods which is having the same method signature.
If you observe the above example, we created an Action delegate object (dlgt) with two input parameters (int) and assigned the methods directly to the delegate object.
Here, the declaration of Action<int, int> dlgt
is same as the SampleDelegate
object in the previous example.
When we execute the above example, we will get the result as shown below.
Add Result: 100
Subtract Result: -80
While creating the Action delegate, we must remember that we can include 0 to 16 input parameters of different types and optional.
In c#, we can also initialize an Action delegate using new
keyword with required input parameters like as shown below.
In c#, we can assign the anonymous method directly to the Action delegate by using the delegate keyword like as shown below.
If you observe the above code, we assigned an anonymous method directly to the Action delegate object (dlgt) using the delegate keyword.
In c#, we can also use Action delegate with lambda expressions. The lambda expressions are the shorthand way of declaring the anonymous method.
Following are the important points which we need to remember about Action delegate in c#.