Click here to Skip to main content
15,881,757 members
Articles / Programming Languages / C#

What is Delegate, Multicast Delegate & Event?

Rate me:
Please Sign up or sign in to vote.
4.60/5 (8 votes)
20 Jun 2014CPOL3 min read 52.4K   20   3
This post discusses what is delegate, multicast delegate and event

Before writing about delegates I would like to introduce you to the problems that we were facing before delegates came into existence.

Heavy Coupling

Heavy coupling between method declaration and definition creates a problem at the time of addition of new method in BusinessLayer, if we do so then it also requires updation in PresentationLayer.

For example:

If we have a Math class in Businesslayer which contain a method called Add(), then to call this method in PresentationLayer, we have to write a line. Now if we add one more method called Substract() in Math class, we have to add one more line in PresentationLayer to call Substract() method.

Delegates

Delegates are abstract pointer towards methods. We can use this abstract pointer to invoke these methods.

Implementation of delegate is a 4 step process:

C#
 public partial class Form1 : Form
{
//1. Declare- public delegate int PointtoAddMethod(int x,int y)
public int Add(int x,int y)
{
return x+y;
}
public void button1_Click(object sender,EventArgs e)
{
//2. Create- PointtoAddMethod myptr= null;
//3. Point- myptr= this.Add();
//4. Invoke- MessageBox.Show(myptr.Invoke(20,10).ToString());
}
} 

How we can achieve decoupling through delegate

We created a web application with 1 aspx page (contain 3 textboxes to get 2 numbers for operation and 1 for choose the operation) and 1 class file.

Class file

C#
public class Class1
{
public delegate int PointerMath(int i, int j);
public PointerMath getpointer(int intoperation)
{
PointerMath objpointer = null;
if (intoperation == 1)
objpointer = Add;
else if (intoperation == 2)
objpointer = Sub;
//else if (intoperation == 3)
// objpointer = Mul;
//else if (intoperation == 4)
// objpointer = Div;
return objpointer;
}
private int Add(int x, int y)
{
return x + y;
}
private int Sub(int x, int y)
{
return x – y;
}
//private int Mul(int x, int y)
//{
// return x * y;
//}
//private int Div(int x, int y)
//{
// return x / y;
//}
}
}

aspx.cs file

C#
public partial class WebForm1 : System.Web.UI.Page
{
////1.decalre delegate
//public delegate int PointertoAddFunction(int x, int y);
protected void Page_Load(object sender, EventArgs e)
{
}
//private int Add(int x,int y)
//{
// return x + y;
//}
protected void Button1_Click(object sender, EventArgs e)
{
////2.create delegate reference
//PointertoAddFunction myptr = null;
////3.point the referance to Add function
//myptr = this.Add;
////4.invoke the method through delegate object
//Label1.Text = myptr.Invoke(10, 20).ToString();
Class1 objMath = new Class1();
int A = Convert.ToInt16(TextBox1.Text);
int B = Convert.ToInt16(TextBox2.Text);
int C = Convert.ToInt16(TextBox3.Text);
int Results = objMath.getpointer(C).Invoke(A, B);
Result.Text = Results.ToString();
}
}

In the above code, as you can see currently I am not using delegate, and I declared and defined only 2 methods Add() and Sub().

Now in this case when we run the above program and if we pass other than 1/2 in Textbox3, then it will not work properly.

If we want to do Multiplication and Division from the same application, then we have to update our class file (Class1). This problem is called Heavy Coupling.

To solve this problem, we can use delegate and to do the same. Please uncomment the above commented code inside protected void Button1_Click(object sender, EventArgs e).

Now if we add Mul and Div in clsMaths class, then we do not want to change in .aspx.cs file only we have to update .aspx file for updating the instructions.

Multicast delegate

Multicast delegate is an extension of normal delegate. It helps you to point more than one method at a single moment of time.

Scenarios where we can use Multicast Delegate

Publisher Subscriber Model- Error Handling through Eventlog, EMail, File, Mobile Methods can done through Multicast Delegate where publisher has a Multicast Delegate which has reference to all methods.

Implementation of Multicast Delegate

In a windows application, we created a button on a form and on the button click, we want to invoke 2 methods (method1(), method2()). So the code of that form.cs is:

C#
public partial class Form1 : Form
{
//1.decalre delegate
public delegate void MyDelegate();
private void Method1()
{
MessageBox.Show("Method1 Invoked");
}
//lock code start
private void Method2()
{
MessageBox.Show("Method2 Invoked");
}
//lock code End
private void button1_Click(object sender, EventArgs e)
{
//2.create delegate referance
MyDelegate myptr = null;
//3.point the referance to Add function
myptr += this.Method1;
////lock code start
myptr += this.Method2;
////lock code end
//4.invoke the method through delegate object
myptr.Invoke();
}
public Form1()
{
InitializeComponent();
}
}

Problems Associated with Multicast Delegates

  1. Subscriber has no authority to decide whether he interested in any event or not.
  2. If we change the program to provide authority to subscriber whether he is interested in event or not, then subscriber has got too much control. This means at that time subscriber can go and call any kind of method, he can make the delegate null.

Event

Event is a higher level of encapsulation over delegates. When we declare an event, then the client/Subscriber can only listen to the Event, He can’t do more than that.

Implementation of Event is a 3 step process.

  1. Declare - public delegate void CallEveryOne()
  2. Create - public Event CallEveryOne objEventCallEveryOne;
  3. Call- objEventCallEveryOne;

Difference between Delegates and Events

When we create an Event, the client can only listen to the Event, where when we create a delegate, the client will get lot of control over application (He can add/remove methods in delegate.).

Implementation of Event

In a Windows application, we created a button on form1, on the button click we have to display current datetime on form2’s label and form3’s label. So the code of that form1.cs is:

C#
public partial class Form1 : Form
{
public delegate void CallEveryOne();
//public CallEveryOne ptr;
public event CallEveryOne ptr;
Form2 obj;
Form3 obj2;
public Form1()
{
InitializeComponent();
}
private void Form1_Load_1(object sender, EventArgs e)
{
obj = new Form2(this);
obj2 = new Form3(this);
obj.Show();
obj2.Show();
}
private void button1_Click_1(object sender, EventArgs e)
{
//ptr.Invoke();
ptr();
}
}

And the code of form2.cs (same for form3.cs) is:

C#
public partial class Form2 : Form
{
Form1 m_form = null;
public Form2(Form1 frm1)
{
InitializeComponent();
m_form = frm1;
m_form.ptr += new Form1.CallEveryOne(CallMe);
}
public void CallMe()
{
label1.Text = "Message Broadcast at" + DateTime.Now.ToString();
}
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
I am "Akash Jain" working in IT Industry from last 6 years. From the beginning of my career I worked with C# for both windows and web application. In my short career I worked for 2 Major ERP Applications, e-commerce applications, CMS based applications and also few static websites.

I am a MCP for web application for ASP.NET 4.0. I have also done PMP training as project management is one of my interest area.

Comments and Discussions

 
QuestionHow to get list of methods pointed by Multicast Delegate ? Pin
Ammar Shaukat22-Jan-18 23:14
professionalAmmar Shaukat22-Jan-18 23:14 
QuestionThanks Akash, here you explained everything what is needed to know about Delegate Pin
RaveendraBj1-Feb-16 5:43
RaveendraBj1-Feb-16 5:43 
Questionvery nice article Pin
Member 361874712-Jun-15 15:34
Member 361874712-Jun-15 15:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.