G
G
Georgy Pelageykin2017-02-06 20:55:39
C++ / C#
Georgy Pelageykin, 2017-02-06 20:55:39

Is it bad form to use a non-EventHandler as the event delegate type?

I often use events in the game code (under Unity3d, to be precise, but mostly in the code decoupled from the engine/scene). After reading Richter, I honestly used EventHandler, but it didn’t bring me anything other than code clutter. I changed it to Action, it became cleaner, I did not notice any problems.
In the CLR via C#, the use of EventHandler with its crutch sender cast and EventArgs.Empty stub was justified by the fact that it is generally accepted and does not force delegates to be produced. You can't argue with the first, but the second has been irrelevant for many years due to the introduction of generic delegates, incl. and built-in Action. If necessary, you can put a typed sender as the first argument (which is obviously cleaner than Object sender), and if you need to pass something, then the second argument will be either one argument of the passed type, if you need to pass an instance of one type, or data packed into the EventArgs heir if there are many.
Less boilerplate code, type safety. What am I doing wrong?
Of course, this means the use in the internal logic of the application, which does not depend on any hundreds of events from WinForms / WPF / etc.
PS I'm surprised that this rather common question was asked in a large number of English speakers, but it is not on the toaster) The opinion of the local audience is interesting.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav Silin, 2017-02-06
@ArXen42

You might be a little surprised, but using events is generally not desirable =)
Since it is very easy to forget to unsubscribe from the event, and this is necessary so that there is no leak. And if you have not forgotten, then very often you will need crutches in the form of caching the object to which you subscribed for further unsubscribing ... Plus problems with lambdas. I try to replace them with IObservable from Reactive Extensions for .Net .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question