Callback Function

Many times we need to implement callback function. So I am wrting about that.
There are 3 ways we can allow to provide callback functionality.


1. Events

2. Delegates

3. Interface



1. Events:
=========

Most often we use that callback to gue based application. Standard Windows control fire events. We set handler against particular event and write our own logic in that event handler. We can use event based callback in our business class also.

Ex.

public class MyForm: Form
{
private Button btnExecute = new Button(); //Standard Windows Button Control
Public MyForm()
{
InitializeComponet();
btnExecute.Click += new EventHandler(OnButtonClick);
}

//Event Handler/CallBack Function
private void OnButtonClick(object sender, EventArgs e)
{
MessageBox.Show("Good Morning");
}
}


Event based callback function usage guideline:

1. When we need to implement method registration/un-registration.

2. More then one object will want notification of the event.

3. Add listen with the help of Visual Designer. Ex GUI based control event.



2. Delegates
===========

Delegates are nothing but similar to function pointer in C. Many times we can use delegate for callback function. There are 2 types of delegates are single cast and another is multicast.

Delegate callback example


public delegate void MyDel;

public class Bangladesh
{
public void GetPM(MyDel d)
{
d.Invoke("Sheck Hasina");
}
}

public class MyForm : Form
{
void OnButtonClick(object sender, EventArgs e)
{
Bangladesh b = new Bangladesh();
MyDel myD = new MyDel(ShowPM);

b.GetPM(myD); //Passing delegate
}

//CallBack Method
void ShowPM(string pm)
{
MessageBox.Show(pm);
}
}

GuideLine of Using Delegate Callback:

1. Want to use C style function pointer.

2. Want to use single callback function.

3. Want registration occur at a constraction time.

4. Notification requirement is to havy with many arguments.


3. Interface:
===========

Message based commpunication technology ex. WCF duplex communication (Chat software) is not possible without Interface based callback.

Ex:

public interface IPMName
{
void GetPMName(string pm);
}

public class Bangladesh
{
public void P1(IPMName p)
{
p.GetPMName("Sheck Hasina");
}
}


public class India
{
public void P1(IPMName p)
{
p.GetPMName("Monmohan Sing");
}
}

public class MyForm : Form, IPMName
{
//Callback method
public void GetPMName(string pm)
{
MessageBox.Show(pm);
}

void OnButtonClick(object sender, EventArgs e)
{
Bangladesh b = new Bangladesh();
b.P1(this);

India i = new India();
i.P1(this);
}
}

Interface based Callback Guideline

1. Use Message based communication application.

2. Anyother complex callback senario.




Reference:
C#/VB .NET Coding GuideLines by Steave Sartain

1 comment:

Razan said...

Good Stuff.Nice Presentation