I have seen various examples of event handling. Here is one: Event Sample.
Sometimes I see the delegate declared outside the class that will raise the event (as in the link above), and sometimes inside (where I think it should be declared).
It makes more sense to me to declare the event inside the class that will raise the event. The reason being that the event that the class will declare is really just some sugar coating for helper methods etc. that are really doing the adding to, subtracting from, and invoking of the delegate etc.
Are there any best practices? Are there times when you would want to declare the delegate outside, and other times where you would want to declare the delegate inside? If so, how should it be decided which to do?
You can declare a delegate that can appear on its own or even nested inside a class.
Use "event" keyword with delegate type variable to declare an event. Use built-in delegate EventHandler or EventHandler<TEventArgs> for common events. The publisher class raises an event, and the subscriber class registers for an event and provides the event-handler method.
Using Delegates with EventsThe events are declared and raised in a class and associated with the event handlers using delegates within the same class or some other class. The class containing the event is used to publish the event. This is called the publisher class.
Delegate is a type that defines a signature and holds a reference of method whose signature matches with the delegate. Event is a notification raised by an object to signal the occurrence of an action. Delegate is associated with the event to hold a reference of a method to be called when the event is raised.
Typically, these days you'd create your own class derived from EventArgs
, and then just use EventHandler<TEventArgs>
- there's no need to create a separate delegate type. So instead of AlarmEventHandler
, you'd use EventHandler<AlarmEventArgs>
. The EventArgs
-derived class should generally be top-level (i.e. non-nested).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With