Using Delegate For Event Handling

By Anoop S

One of the main uses of delegates is for handling the events

Suppose we have some object of some class X and we want to offer the ability to register method that will be called when the object changes. Suppose that each of this method has a header like

void MethodName()

We can introduce a delegate type to describe this

delegate  void Handler()

In the class X we can declare a public field  to be of this type. Here is an example

public  class X
{
private int iValue =0;
public Handler uHandler=null;
public void inc()
{
iValue++
uHandler();
}
}

In client class, we can then do:

X xt =new X();
tX.uHandler  +=  new Handler(Fred);
tX.uHandler  +=  new Handler(Bert);

where Fred and Bert are appropriate methods.
If we do this, then whenever there is a call of inc, the methods Fred and Bert will also be called.
Although this will work, the uHandler field of X is very vulnerable.  Any client can do anything it wants to it. For eg:

tX uHandler =null;

In order to prevent this uHandler  should be declared with keyword event as in :

public  event Handler uHandler =null;

if you do this client can only execute += or -=  operators on uHandlers


Using Delegate For Event Handling  (1784 Views)