Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a delegate be declared inside the class that will raise the event, or outside?

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?

like image 388
richard Avatar asked Mar 13 '11 08:03

richard


People also ask

Can we declare delegate inside class?

You can declare a delegate that can appear on its own or even nested inside a class.

How do you declare an event based on the delegate?

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.

How events are handled through delegates?

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.

What is an event and a delegate ?- How are they related?

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.


1 Answers

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).

like image 144
Jon Skeet Avatar answered Sep 24 '22 03:09

Jon Skeet