Delegates in C#


Delegates is a type which holds the method(s) reference in an object. It is also referred to as a type safe function pointer. Delegates are roughly like from pointers in C++; however delegates are type safe and secure.
A delegate instance can encapsulate a static or a non-static method, also and call that method for execution. Effective use of a delegate improves the performance of applications.
Method can be called in 2 different ways in C#, those are:
Using instance of a class if it is non-static and name of the class if it is static.
Using a delegate (either static or non-static).
To call a method by using delegate we need to adopt the following process:
Define a delegate
Instantiate the delegate.
Call the delegate by passing required parameters values.
Syntax to define a Delegate:
[<modifiers>]delegate void [<type>Name([<Parameter List>])
Note: While defining a delegate you should follow the same signature of the method i.e parameters of delegate should be same as the parameters of method and return types of delegates should be same as the return types of method, we want to call by using the delegate.
public void AddNums(int x, int y)
{
Console.WriteLine(x+y);
}
public delegate void AddDel(int x, int y);
public static string SayHello(string name)
{
return “Hello” + name;
}
public delegate string SayDel(string name);
Instantiate the delegate : In this process we create the instance of the delegate and bind the method we want to call by using the delegate to the delegate.
AddDel ad = new AddDel(AddNums); or AddDel ad = AddNums;
SayDel sd = new SayDel(SayHello); or SayDel sd = SayHello();
Calling the delegate: Call the delegate by passing required parameter values, so that the method which is bound with delegate gets executed.
ad(10,20); ad(30,20); ad(50,30)
string s1 = sd(“Raju”); string s2 = sd(“Suneetha”); string s3 = sd(“Srinivas”);
Where to define a delegate?
→ Delegates can be defined either in a class/structure or with in a namespace just like we define other types.
Add a code file under the project naming it as Delegate.cs & Write the following code:
Multicast Delegate: It is a delegate who holds the reference of more than one method. Multicast delegates must contain only methods that return void. If we want to call multiple methods using a single delegate all the method should have the same Parameter types. To test this, add a new class DelDemo2.cs under the project and write the following code:
In next blog we will see Anonymous Methods.
Subscribe to my newsletter
Read articles from Dev_Naren directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Dev_Naren
Dev_Naren
I am a software developer. Exploring tech world. I just post my thoughts about tech and anythings which I'm curious about.