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
{
public int Add(int x,int y)
{
return x+y;
}
public void button1_Click(object sender,EventArgs e)
{
}
}
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;
return objpointer;
}
private int Add(int x, int y)
{
return x + y;
}
private int Sub(int x, int y)
{
return x – y;
}
}
}
aspx.cs file
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
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
{
public delegate void MyDelegate();
private void Method1()
{
MessageBox.Show(“Method1 Invoked”);
}
private void Method2()
{
MessageBox.Show(“Method2 Invoked”);
}
private void button1_Click(object sender, EventArgs e)
{
MyDelegate myptr = null;
myptr += this.Method1;
myptr += this.Method2;
myptr.Invoke();
}
public Form1()
{
InitializeComponent();
}
}
Problems Associated with Multicast Delegates
- Subscriber has no authority to decide whether he interested in any event or not.
- 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.
- Declare -
public delegate void CallEveryOne()
- Create -
public Event CallEveryOne objEventCallEveryOne;
- 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 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();
}
}
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();
}
}