A delegate is essentially a collection of one or more references to methods with identical method signatures. In c#, +
(or +=
) is used to add new methods to the delegate and -
(or -=
) is used to remove methods from the delegate.
An event is something that can be raised in the code to then call all the methods connected to its delegate. Events almost always have delegates that return void
with two arguments: Object sender
and the event arguments, which are always a class derived from System.EventArgs
.
For example, if I wanted to write an event OnCookFood in my Chef class. Note: This assumes I wrote a CookEventArgs
class first, because I'd presumably want to pass what kind of food my Chef is cooking.
// modifier delegate void HandlerName(Object sender, EventArgsClass e)
// modifier event HandlerName EventName
public delegate void CookFoodHandler(Object sender, CookEventArgs e);
public event CookFoodHandler OnCookFood;
// More code...
OnCookFood(new CookEventArgs("Pie"));
Of course, this is the hard way to do it. You can use the EventHandler<T>
class to have the compiler create the delegate for you:
public event EventHandler<CookEventArgs> OnCookFood;
// More code...
OnCookFood(new CookEventArgs("Pie"));
and finally, to add a handler; assuming we have an object cook
:
void HandleCooking(Object e, CookEventArgs e) {
// Do something here
}
// in another function, probably the constructor...
cook.OnCookFood += HandleCooking;