affiliate_link

Monday, March 12, 2018

What is Action Delegate?

Microsoft introduced some pre-built delegates so that we don't have to declare delegates every time. Action is one of the pre-built delegates.

Action in C# represents a delegate that has void return type and optional parameters. There are two variants of Action delegate.
  1. Action
  2. Action<in T>

Non-Generic Action Delegate

First variant is non-generic delegate that takes no parameters and has void return type. In this Action delegate, we can store only those methods which has no parameters and void return type.
 








static void Main(string[] args)
{
    Action doWorkAction = new Action(DoWork);
    doWorkAction(); //Print "Hi, I am doing work."
}
 
public static void DoWork()
{
    Console.WriteLine("Hi, I am doing work.");
}
 
We can also store method in the Action delegate with direct initializing with the method. Below is the example.










static void Main(string[] args)
{
    Action doWorkAction = DoWork;
    doWorkAction(); //Print "Hi, I am doing work."
}
 
public static void DoWork()
{
    Console.WriteLine("Hi, I am doing work.");
}

Generic Action Delegate

We can also store method in the Action delegate with direct initializing with the method.

We have to choose Action delegate according to the method, which we want to store. If our method takes two parameters, then we have to choose action delegate which has two parameters Action<in T1, T2>(T1 arg1, T2 arg2). Below are some examples


static void Main(string[] args)
{
    Action<int> firstAction = DoWorkWithOneParameter;
    Action<int, int> secondAction = DoWorkWithTwoParameters;
    Action<int, int, int> thirdAction = DoWorkWithThreeParameters;
 
    firstAction(1); // Print 1
    secondAction(1, 2); // Print 1-2
    thirdAction(1, 2, 3); //Print 1-2-3
}
 
public static void DoWorkWithOneParameter(int arg)
{
    Console.WriteLine(arg);
}
 
public static void DoWorkWithTwoParameters(int arg1, int arg2)
{
    Console.WriteLine(arg1 + "-" + arg2);
}
 
public static void DoWorkWithThreeParameters(int arg1, int arg2, int arg3)
{
    Console.WriteLine(arg1 + "-" + arg2 + "-" + arg3);
}

Action with Lambda Expression

We can use Lambda expression with Action delegate. Below is the example.





















static void Main(string[] args)
{
    Action act = () =>
    {
        Console.WriteLine("No Parameter");
    };
 
    Action<int> actWithOneParameter = (arg1) =>
        {
            Console.WriteLine("Par: " + arg1);
        };
 
    Action<int, int> actWithTwoParameter = (arg1, arg2) =>
        {
            Console.WriteLine("Par1: " + arg1 + ", Par2: " + arg2);
        };
 
    act();
    actWithOneParameter(1);
    actWithTwoParameter(1, 2);
}

No comments: