Loading...

Action is also a delegate type included in the System namespace. An Action type delegate is the same as Func delegate except that the Action delegate does not return any value. You can say, an Action delegate can be used with a method that has a void return type. An Action delegate can take up to 16 input parameters of different types.

We can use an Action delegate instead of defining the any delegate, for example:

static void Print(int i)
{
    Console.WriteLine(i);
}
static void Main(string[] args)
{
    Action<int> printAction = Print;
    printAction(10);
}


We can initialize an Action delegate using the new keyword or by directly assigning a method:

Action<int> printAction = Print;
// Or
Action<int> printAction = new Action<int>(Print);



Anonymous method with Action delegate

static void Main(string[] args)
{
    Action<int> printAction = delegate(int i)
    {
      Console.WriteLine(i);
    };
    printAction(10);
}



Lambda expression with Action delegate

static void Main(string[] args)
{
    Action<int> printAction = i => Console.WriteLine(i);       
    printAction(10);
}




Advantages of Action Delegates

  1. Easy and quick to define delegates.
  2. Makes code short.
  3. Compatible type throughout the application.

 Things to be remember when using Action delegate :

  1. Action delegate does not return anything. Return type must be void.
  2. Action delegate can have 1 to 16 input parameters.
  3. Action delegate can be used with anonymous methods or lambda expressions.