Working with .NET Events
This section discusses .NET event-design guidelines and development practices that promote loose coupling between publishers and subscribers, improve availability, conform to existing conventions, and generally take advantage of .NET’s rich event-support infrastructure. Another event-related technique (publishing events asynchronously) is discussed in Chapter 7.
Defining Delegate Signatures
Although technically a delegate declaration can define any method signature, in practice, event delegates should conform to a few specific guidelines.
First, the target methods should have a void
return type. For example, for an event dealing with a new value for a number, such a signature might be:
public delegate void NumberChangedEventHandler(int number);
The reason you should use a void
return type is that it simply doesn’t make sense to return a value to the event publisher. What should the event publisher do with those values? The publisher has no idea why an event subscriber wants to subscribe in the first place. In addition, the delegate class hides the actual publishing act from the publisher. The delegate is the one iterating over its internal list of sinks (subscribing objects), calling each corresponding method; the returned values aren’t propagated to the publisher’s code. The logic for using the void
return type also suggests that you should avoid output parameters that use either the ref
or out
parameter modifiers, because the output parameters of the various ...
Get Programming .NET Components, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.