Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

What is Delegate, Multicast Delegate & Event?

0.00/5 (No votes)
20 Jun 2014 1  
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:

 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

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

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:

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:

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:

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here