Lect05 - Events
Lect05 - Events
Objectives:
Learn about delegates, how to create them and how to use them.
Learn about special types of delegates called events.
Learn how to use the standard event handler.
1. Delegates
To see how delegates are declared and used, consider the following
example.
Example 1:
using System;
Instantiating a Delegate
Before you create an instance of a delegate, you must have a method
that you wish to associate that instance with. As we can see from the
example, the syntax is:
DelegateType delegateVar = new DelegateType(methodName);
Notice that the method name must NOT be followed with parameters.
Actually a method name without parameter means a reference to the
method. So the above statement assigns the method reference to the
delegateVar delegate instance.
Multicast Delegates
Internally, a delegate uses a linked list to hold references to the methods
associated with it. Thus, a delegate instance can hold references to more
than one method.
Invoking a Delegate
As we saw in the example, a delegate instance is invoked based on its
method-like signature. In our example, since the associated methods
are void, we simply call it as:
d(string)
2. Events
That is, a class representing a GUI control such as the Button class will
declare a public field for a delegate which it will invoke when the button
is clicked.
When the user clicks the button, the method is automatically executed.
This procedure will work fine except for one problem – the delegate field
is public.
This means other classes (other than the Button class) can invoke the
delegate - thus raising a false alarm. In fact, the field can be assigned a
new instance by another class – thus canceling any registration to the
delegate made by other classes.
}
}
}
//speed up
for (int i=0; i<10; i++)
myCar.Accelerate(20);
//no response
for (int i=0; i<10; i++)
myCar.Accelerate(20);
}
where source is the object that fired the event and e contains any
additional information about the event.
However, the EventArgs class is a class that does not have any fields that
can be used to pass the event information to the client.
Example 3: The following example modifies the Car example to use the standard Event Handler
class.
using System;
}
}
}
//speed up
for (int i=0; i<10; i++)
myCar.Accelerate(20);
//cancel registration to events
myCar.Exploded -= new EventHandler(OnExplod);
myCar.AboutToExplod -= new EventHandler(OnAboutToExplod);
//no response
for (int i=0; i<10; i++)
myCar.Accelerate(20);
}