C
C#3mo ago
occluder

✅ Is there a reason to still be using EventArgs and EventHandler<T> for events?

I see the usage of both aforementioned types in the msdocs for events. Even in new-ish blogs and packages, I see some people still using this approach. However, I fail to see a point to it. Event declarations can be of any delegate, like Action<T> or Func<T, T>. And EventArgs seems utterly pointless. So, I just want to make sure: Is this just an outdated convention? Or are there secret runtime benefits of doing events this way?
2 Replies
SWR
SWR3mo ago
It's not necessary, no. It's just a windows conformance thing. The EventHandler delegate provides two things that can be very useful. 1. The object sender let's the event subscriber know who sent the event. You don't always need this. Sometimes you never need it, and sometimes the type could be guaranteed and defined, but including an object just covers every case. 2. The EventArgs is a base class. If someone decided to override some component class you made that contained events, and wanted to create a new event that internally triggered one of your events, they could do so and pass their derived event data if needed. If they needed to make a specialized EventArgs that held data and needed to pass it to one of your base events, this is possible because the base type is still EventArgs. Events in C# are designed with an external subscriber in mind. We have no idea what they will use the event for, but we want to give them the option to do anything they need and not add any restrictions. So yes, you can make an event of any delegate type, but it may hurt your scalability or subscribers to your events.
occluder
occluderOP3mo ago
@SWR Thanks for the detailed response
Want results from more Discord servers?
Add your server