top of page

Func and Action Delegates in C#

  • Writer: Raghav Kumar
    Raghav Kumar
  • Mar 18
  • 2 min read



What are the Delegates?


A delegate in C# is a type-safe function pointer that allows you to pass methods as parameters. It defines a method's signature and holds a reference to a method with a matching signature, making it possible to invoke methods dynamically at runtime.


Declaration of Delegates


[modifier] delegate [return_type] [delegate_name] ([parameter_list]);

  • modifier: It is the required modifier that defines the access of the delegate, and it is optional to use.

  • delegate: It is the keyword that is used to define the delegate.

  • return_type: It is the type of value returned by the methods which the delegate will be going to call. It can be void. A method must have the same return type as the delegate.

  • delegate_name: It is the user-defined name or identifier for the delegate.

  • parameter_list: This contains the parameters which are required by the method when called through the delegate.


Example:


// "public" is the modifier
// "int" is return type
// "DelegatesName" is delegate name
// “(int A, int B, int C)” are the parameters

public delegate int DelegatesName(int A, int B, int C);

Func and Action Delegates


Func and Action delegates in C# are powerful tools for creating and working with functions flexibly and dynamically. They play a crucial role in functional programming and can be used to define and pass around functions as parameters or return values.


Func Delegate with One Parameter:


public static int DoubleValue(int num)
{  
    return num + num;  
}  

static void Main()  
{  
    // Func delegate with one input and one return type  
    Func<int, int> Delegate = DoubleValue;  
    Console.WriteLine(Delegate(10));  
}

Output:

20

Func Delegate with Anonymous Method:


Func<int, int, int> sum = delegate (int x, int y) 
{ 
   return x + y; 
};  

Console.WriteLine(sum(6, 8));

Output:

14

Func Delegate with Lambda Expression:


static void Main()
{
   Func<int, int, int> sum = (x, y) => x + y;  
   Console.WriteLine(sum(6, 8)); 
}

Output:

14

Action Delegate with no parameter:


public static void PrintMessage()
{
   Console.WriteLine("Hello, World");
}

static void Main()
{
   // Using Action delegate with no parameters
   Action action = PrintMessage;
   action();  
} 

Output:

Hello, World

Action Delegate with Two Parameters:


public static void SubtractNumbers(int p, int q)
{
   Console.WriteLine(p - q); 
}

static void Main()
{
   // Using Action delegate with two parameters
   Action<int, int> action = SubtractNumbers; 
   action(20, 5); 
}

Func Vs Action Delegates


The main difference between Func and Action lies in their return types. The Func delegate allows you to specify a return type, whereas the Action delegate does not return a value. Both delegates can have up to 16 parameters.


Happy coding and learning!

Comments


bottom of page