Friday, July 20, 2007

Difference between Delegate and Delegate With event

Is there any difference between the delegate and delegate with event ?...

Yes... See the sample



delegate void UpdateControl( string text);
UpdateControl m_UpdateControl = null;
private event UpdateControl m_EventUpdateControl = null;


m_UpdateControl += new UpdateControl( UpdateListCtrl);
m_EventUpdateControl += new UpdateControl( UpdateListCtrl);

private void UpdateListCtrl()
{
listSent.items.Add("Test" + listSent.items.count);
}




we can create the object as follows :

m_UpdateControl = new UpdateControl(UpdateListCtrl); // will work properly

But the following code will not work properly...

m_EventUpdateControl = new UpdateControl(UpdateListCtrl);

we have to change it as

m_EventUpdateControl += new UpdateControl(UpdateListCtrl);

This implies...
we can set the delegate object as null as follows in anywhere like during initialization or within any fn.


m_UpdateControl = null;


But for Event with delegate object, we will not be able to initialize it as null , it affects the other client's delegates also.

m_EventUpdateControl = null; // Exception : we can initialize null for the event with delegate object during initialization.


what it means is that if we use the event keyword no client class can set it to null. This is very important. Multiple clients can use the same delegate. After multiple client have added a function to listen to the callback of the delegate. But now one of the client sets the delegate to null or uses the = sign to add a new call back. This means that the previous invocation list will not be used any more. Hence all the previous client will not get any of the callback even if they have registered for the call back.

Hence we can say that the even keyword adds a layer of protection on the instance of the delegate. The protection prevents

any client to reset the delegate invocation list. They can only add or remove the target from the invocation list.

No comments: