0

Reading the official guidelines on publishing events in .NET it says:

Although events in classes that you define can be based on any valid delegate type, even delegates that return a value, it is generally recommended that you base your events on the .NET Framework pattern by using EventHandler, as shown in the following example.

The documentation also mentions that The .NET Framework 2.0 introduces a generic version of this delegate, EventHandler.

It then goes on to show an example using EventHandler, but also an example using a custom delegate type.

Given that it looks like the custom delegate pattern is not strongly discouraged (it even has an official example), is it ever beneficial to create our custom delegates instead of subclassing EventArgs and using EventHandler<CustomEventArgs>?

Community
  • 1
  • 1
Marcell Toth
  • 3,433
  • 1
  • 21
  • 36
  • Well, not really, i guess. Although, if you have several events in a class that all feature the same EventArgs type (like `EventHandler`), it could be somewhat beneficial for code readability (or documentation of APIs) to use custom event delegate types with different meaningful descriptive names. (Yeah, i am stretching it here a bit, possibly) –  Nov 18 '18 at 19:36
  • 1
    I would argue that `EventHandler` is actually more readable than `SomeEventDelegate`. Looking at the former, I instantly know its signature, while the later, I have to take a closer look – Marcell Toth Nov 18 '18 at 19:49
  • I can't think of any particular advantage of delegate properties over event handlers. Contrariwise, an advantage of events over delegates is that serializers ([other than `BinaryFormatter`](https://stackoverflow.com/q/2308620)) know to never serialize events, but will sometimes try to serialize delegate members. See e.g. [C# Deserialize an object which is derived and has references](https://stackoverflow.com/a/42602946) for an example of the troubles this can cause. – dbc Nov 18 '18 at 20:00

0 Answers0