I hate EventHandler. I hate that I have to cast the sender if I want to do anything with it. I hate that I have to make a new class inheriting from EventArgs to use EventHandler<T>.
I’ve always been told that EventHandler is the tradition and blah, blah…whatever. But I can’t find a reason why this dogma is still around.
Is there a reason why it would be a bad idea to make a new delegate:
delegate void EventHandler<TSender, T>(TSender sender, T args);
That way the sender will be typesafe and I can pass whatever the heck I want as the arguments (including custom EventArgs if I so desire).
There actually is a good reason for requiring the second argument to derive from
EventArgsif your fully-trusted code hosts third-party code as partially-trusted.Because the callback to the event handling delegate is done in the context of the raising code and not the third party code, it is possible for malicious third-party code to add a privileged system operation as an event handler and thus potentially execute an escalation of privilege attack by running code in your fully-trusted context that their partially-trusted context could not run.
For example, if you declare a handler as type
int -> voidthen the third-party code could enqueueYourEvent += Enviroment.Exit(-1)and have you exit the process unintentionally. This would obviously cause an easy-to-detect problem, but there are far more malicious APIs that could be enqueued to do other things.When the signature is
(object, EventArgs) -> voidthen there are no privileged operations in the framework that can be enqueued because none of them are compatible with this signature. It’s part of the security code review in the framework to ensure this (unfortunately I cannot find the source where I read this).So in certain circumstances there are valid security concerns as to why you should use the standard pattern. If you’re 100% sure your code will never be used in these circumstances then the event signature guideline isn’t as important (apart from other developers thinking WTF), but if it might be then you should follow it.