Delegates In C#

Introduction

Delegates are not necessary but we use them to improve the security of the class data member function. Delegates are more useful when we need to hide the actual name of the function before going in detail that what delegates are, I want to explain why there are delegates.

Need of delegates

Whenever we want to make our methods more secure we can create a delegate and make our methods more secure. Even we can access the private member function without using their name with the help of delegates.

What are delegates

A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance. It is similar to C/C++ pointer to function.

Syntax to create delegate

[Access specifier] delegate [return type] name of the delegate (parameter list).

Here,

  • Access specifier - indicates the accessibility of delegate.
  • Delegate - it’s a keyword that defines the delegate.
  • name of the delegate - here we write the name of the delegate.
  • parameter list - here we pass the parameter that match with signature of the function.

Example

public delegate int PerformCalculation(int x, int y);

explanation

This delegate can call any method that matches its signature means that return type and parameters must be same in both delegate and function, we have to just pass the function to the delegate.

How to use delegates

We can simply assign method to the delegate by creating an object of delegate and assigning function to them

Let’s have a look,

  • Delegate name object_naame = new Delegate name(function name);
  • Next we can call the function with the object of the delegate
  • object_naame(parameter);// calling the method without using the name of the method

Example

using System;

delegate int numMath(int n);
namespace delegates {
    class TestDelegate {
        static int num = 10;
        public static int AddNum(int p) {
            num += p;
            return num;
        }
        public static int MultNum(int q) {
            num *= q;
            return num;
        }
        public static int getNum() {
            return num;
        }
        static void Main(string[] args) {
            //create delegate instances
            numMath nc1 = new numMath(AddNum);
            numMath nc2 = new numMath(MultNum);
            //calling the methods using the delegate objects
            nc1(25);
            Console.WriteLine("Value of Num: {0}", getNum());
            nc2(5);
            Console.WriteLine("Value of Num: {0}", getNum());
            Console.ReadKey();
        }
    }
}

Explanation 

Here first of all we created a Delegate with name numMath who returns an integer value

delegate void numMath(int n);

 Then we created a simple class named testDelegate.

 class TestDelegate

Here we declared  a static variable two static functions named AddNum and MultiNum with the same signature as well as Delegate and one method named getNum that returns the value of our static variable num

static int num = 10;

public static void  AddNum(int p)
{
    num += p;        
}
public static void MultNum(int q)
{
    num *= q;
}
public static int getNum()
{
    return num;
}

Next we created two objects of the Delegate nc1 and nc2 and assign them AddNum and MultiNum.

//create delegate instances
numMath nc1 = new numMath(AddNum);
numMath nc2 = new numMath(MultNum);

Now we can call these functions with these objects 

//calling the methods using the delegate objects
nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum());

After compilation, this code produces this output.

Output

 

Note
We can also remove and reassign the same delegate by using,

  • += :to reassign a new function to same delegate
  • -= : to remove the passed function to the delegate

Let's have an example

 nc1(25);
 Console.WriteLine("Value of Num: {0}", getNum());
 nc1-= new numMath(AddNum); //removing the AddNum from the nc1
 nc1 += new numMath(MultNum);//Re assigning the another method multNum
 nc1(5);         

Explanation 

Here we called both methods by using single Delegate object by re-assigning them this will also produce the same out-put

Points to keep in mind while using the Delegates

  • Delegates are useful when we don't want to reveal the name of the method.
  • The signature of the Delegate and function must be same otherwise you have to face errors.
  • To re-assign a new function to an old created instance of the delegate we use += but the signature must be same 
  • To remove a previously assigned function we used -=.


Similar Articles