Alex Rivera | Logout

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

Asked 2011-03-13T08:14:18.133
14

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?

Edit
Report

1 Answer

6

I would declare them outside as they are ment to be used by other classes as well - the consumers of the event. I would keep the delegate in the same file as the class if the delegate is specific to this class.

It's less of the problem if you use generic version of EventHandler<TEventAgrs>, available in .NET 2.0 and newer, as you need to declare your custom EventArgs only.

answered 2011-03-13T08:16:50.093

Your Answer