find and solve || findandsolve.com
Please wait.....

C# - Action Delegate

In C#, The Action is a delegate type defined in the System namespace. It is the same as a Func delegate except that the Action delegate doesn't return a value. An Action delegate can be used with a method that has a void return type.

C# Delegate

 using System;					

 public class Program
 {
 public delegate void Print(int val);
 public static void ConsolePrint(int i)
  {
     Console.WriteLine(i);
  }
  public static void Main(string[] args)
  {
    Print prnt = ConsolePrint;
    prnt(15);
  }
}

Output

15

We can use an Action delegate instead of defining the above Print delegate like as given below:


C# Action Delegate Example

using System;					

public class Program
{
 public static void Main()
 {
  Action<int> test = Test;
  //Or
  //Action<int> printActionDel = new Action<int>(ConsolePrint);
     test(25);
 }
 public static void Test(int i)
 {
  Console.WriteLine(i);
 }
}

Output

25

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

Action<int> test= Test;
//Or
Action<int> test= new Action<int>(Test);

An Action delegate can take up to 16 input parameters of different types.

An Anonymous method can also be assigned to an Action delegate like as given below:

using System;					

public class Program
{
 public static void Main()
 {
  Action<int> test = delegate(int i)
  {
    Console.WriteLine(i);
     };
     test(25);
 }
}

Output

25

We can also use a Lambda expression with an Action delegate:


Lambda expression with Action delegate

using System;					

public class Program
{
 public static void Main()
 {
  Action<int> test = i => Console.WriteLine(i);
     test(25);
 }
}

Output

25


Advantages of Action and Func Delegates

  • Easy and quick to define delegates.
  • Makes code short.
  • Compatible type throughout the application.