Delegates in C#

pencil, notes, chewed

You can consider this topic as a basic of advance features. The basic knowledge of c# is must to go through this post Delegates in C#.

Delegates in C#

Delegates in c# are the type-safe pointer of any method. Programmers often needs to pass a method as a parameter of other methods, that’s why delegates comes into the picture.

You can define variables of delegate, just like other data type. These datatype can refer to any method with the same signature as the delegate.

Steps involved while working with delegates:

  1. Declare a delegate
  2. Set a target method
  3. Invoke a delegate

Its quite confusing to understand, to get a better look consider the example below:

Delegate Syntax

[access modifier] delegate [return type] [delegate name]([parameters])

Singlecast Delegate with example

You can set and invoke a delegate in c# in three different ways as explained below:

using System;
					
public class Program
{

	public delegate void ThoughtGem(string msg); //Step1: declaring a delegate

	
	public static void Main()
	{

		 ThoughtGem del = new ThoughtGem(TGA); //Step 2: Set a Target  
        del.Invoke("Hello World"); //Step 3: Invoking a delegate   

        del = TGB; //Step 2: Set a Target 
        del("Hello World"); //Step 3: Invoking a delegate  

        del = (string msg) => Console.WriteLine("Called lambda expression: " + msg); //Step 2: Set a Target 
        del("Hello World");// Step 3: Invoking a delegate  
	}
	
   static void TGA(string message)
    {
        Console.WriteLine("Called TGA() with parameter: " + message);
    }

    static void TGB(string message)
    {
        Console.WriteLine("Called TGB() with parameter: " + message);
    }

}

Multicast Delegate with example

When delegates in c# point to multiple methods, and when it does that it is known as multicast delegate. The + operator is used to compose a delegate and – operator is used to remove the component from the delegate.

using System;
					
public class Program
{
	public delegate int ThoughtGem(int n); //declaring a delegate
	
	
	public static void Main()
	{
		ThoughtGem del1 = new ThoughtGem(TGA);
        del1.Invoke(100);

       	ThoughtGem del2 = TGB;
		del2+=del1; //multicasting the delegate
        del2(200);
		
		del2-=del1; //Removing the multicasting
        
		del2(200);
		
		ThoughtGem del3 = (int n) => { Console.WriteLine("Called lambda() with parameter: " + n); return n;};
		del3+=del1;
        del3(300);
	}
	
   static int TGA(int number)
    {
	   
        Console.WriteLine("Called TGA() with parameter: " + number);
        return number;
    }

    static int TGB(int number)
    {		
        Console.WriteLine("Called TGB() with parameter: " + number);
		return number;
    }

}

Output of above code will be.

Called TGA() with parameter: 100
Called TGB() with parameter: 200
Called TGA() with parameter: 200
Called TGB() with parameter: 200
Called lambda() with parameter: 300
Called TGA() with parameter: 300

C# – Func and Action Delegate

The Func and action delegates in c# are inbuilt generic type of delegates. You can use them with anonymous methods and lambda expressions.

As per Microsoft official website Func delegate can be declared as follow. The last parameter is the type of TResult and is the output parameter, the parameter before the last parameter are input parameters.

public delegate TResult Func<in T,out TResult>(T arg);

The Action delegate do not have any return type and can be declared as follows:

public delegate void Action<in T>(T obj);

The best part of using Func and Action Delegates are you do not have to explicitly define a delegate that encapsulates a method with parameters.

By using Lambda Expression below we can define a method to calculate Sum of two numbers in a Func delegate where first two parameter are passed as input and third parameter as output.

Func<int, int, int>  Sum  = (x, y) => x + y;

You can rewrite the above code as method as well and use a Func delegate to call it like below:

 static int Sum(int x, int y)
    {
        return x + y;
    }

 static void Main(string[] args)
    {
        Func<int,int, int> add = Sum; //Creating a Func type delegate this can be rewritten as lambda also

        int result = add(10, 10);

        Console.WriteLine(result); 
    }

Same goes with Action methods but they are of void types:

Action<int> printData= i => Console.WriteLine(i);
printData(10);

This is how Delegates generally work in c#.

Happy Coding!!

Further Reading:

Dependency Injection in C#
Difference between let, var and const in JavaScript with Hoisting

1 thought on “Delegates in C#”

  1. Pingback: Covariance and Contravariance in C# - Thought Gem

Leave a Comment

Your email address will not be published. Required fields are marked *