Introduction
When I first hear about delegates and events I searched in internet to get an easily understandable article or tutorial , but unfortunately most of the examples and tutorials taken me to the dark areas of confusion and finally I landed up in no mans land. This is the sole purpose of writing a most simplified article about delegates and events.
What is Delegate?
Delegate is nothing but function pointer in C++.(Function Pointers are pointers, i.e. variables, which point to the address of a function. You must keep in mind, both executable compiled code and variables gets a certain space in memory. Instead of calling a method by its we are calling the method with the address location of it in the memory)
Let's go to write your First Delegate
using System;
namespace DElegate
{
/// <summary>
/// Summary description for Hello.
/// </summary>
class Hello
{
//Step 1. Declaring a delegate which can carry address of anyfunction who dont take any parameters
public delegate void MyHelloDelegate();
//Step 2.A normal class member function
public void SayHello()
{
Console.WriteLine("Say hello to the world through delegate");
}
/// <summary>
/// Main Entry point
/// </summary>
[STAThread]
static void Main(string[] args)
{
//Creating a class object to call any methods of your class
Hello classObject=new Hello();
//Step 3.Creating a delegate object and pass the address of the function you want to call
//through the delegate
MyHelloDelegate helloDelegateObj=new MyHelloDelegate(classObject.SayHello);
//Step 4. Call the function through delegate.Ie through function pointer
helloDelegateObj();
//Belive me you are done
Console.ReadLine();
}
}
}
Believe me you are done with your delegate. In the above code if you add a few more code if you want to pass any parameter in delegate.
//Step1
public delegate void MyHelloDelegate1(string s);
//Step2
public void SayHello1(string name)
{
Console.WriteLine("{0} Say hello to the world through delegate",name);
}
//Step3
MyHelloDelegate1 helloDelegateObj1=new MyHelloDelegate1(classObject.SayHello1);
//Step4
helloDelegateObj1("arun");
That’s all about delegates. Remember delegates always use in conjunction with Events. We have to only worry that the function signature is matching with your delegate or not. Moreover delegates are not part of any class, you can use the same delegate for any class of your concern but the only mandatory thing is your function signature matches with delegate declaration.