«^»
11.1. Using delegates for event handling

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

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

void MethodName()

In C#, 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 a client class, we can then do:

X tX = 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, e.g.:

tX.uHandler = null;

To prevent this, uHandler should be declared with the keyword event as in:

public event Handler uHandler = null;

If you do this, clients can only execute the += or -= operators on uHandler.