What is Delegate, Multicast Delegate & Event?

Before writing about Delegates I would like to introduce you about the problems that we are facing before delegate come in existence.

Heavy Coupling- Heavy coupling between method declaration and definition creates problem at the time of addition of new method in BusinessLayer, if we do so then it also require updation in PresentationLayer.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 referance

//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 above program and if we pass other then 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 than we do not want to change in .aspx.cs file only we have to update .aspx file for update the instructions.

Multicast delegate- Multicast delegate is an extension of normal Delegate, It helps you to point more than one method at a single movement 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 have 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 Delegates1.

1. Subscriber has no authority to decide that is he interested in any event or not.

2. If we change the program to provide authority to subscriber that is he interested in event or not, then subscriber got too much control. 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 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();

}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s