Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does basic EventArgs class exist

Tags:

c#

oop

events

this is more theoretical question. I know that every event in C# has to have 2 parameters: object and eventargs. It's clear. But why does the basic eventargs class even exist when it's impossible to pass any data with it? Of course I can make new EventArgs class that inherits from the basic one, but I just miss the point of the class that can't carry any data.

like image 294
czubehead Avatar asked May 24 '15 20:05

czubehead


1 Answers

This is about future-proofing your code.

The theory goes that if at some point you discover that your code should publish more data to event handlers than it did before, you can easily just add more properties to the object you pass to those event handlers.

If, for some reason, the class that holds those data is not under your control you inherit from it, and add your properties to the inherited class. So far so good.

But, if you never passed any object to the event handler in the first place, you cannot add a new parameter to the event delegate without existing code breaking.

As such, that you pass what amounts to a dummy object, EventArgs.Empty to events now give you the ability to later on inherit from EventArgs and start passing data to the same events, without having to change the event handlers at all. I most cases, you don't even have to recompile assemblies that uses the event handler.

So EventArgs is just a handy class you pass to event handlers, you could just as easily create your own, but since it has no meaning except to be a placeholder for possible future changes, there's no need to create your own, simply use EventArgs.

like image 150
Lasse V. Karlsen Avatar answered Oct 05 '22 07:10

Lasse V. Karlsen