Fulproof
Fulproof

Reputation: 4636

Why to substitute EventArgs by generic parameter if the event does not generate data?

I am having difficulties to understand the following phrase from from MSDN EventHandler Delegate:

Do I understood correctly that that the data generated by an event is stored in an instance of EventArgs?

Collateral curiosity:
Does this phrase mean that if the event generate data then don't use generic type EventArgs? Why?

The main question is:
Why to bother about EventArgs (to make it generic or leave it non-generic), if the event does not generate data?

Update:
From the mentioned article and the enclosed in it code example I understood that instead of delegate:

public delegate void EventHandler(Object sender, EventArgs e)

I am to use

public delegate void EventHandler<EventArgs>(Object sender, EventArgs e)   

when my event does not generate data.

Upvotes: 1

Views: 550

Answers (2)

jam40jeff
jam40jeff

Reputation: 2596

There is no advantage to the second over the first if you are just using EventArgs. The documentation likely just didn't mention this second possiblity as it was easier just to show the single delegate definition with the generic parameter in all of the examples.

Also, it is common to pass EventArgs.Empty rather than null.

If you event does have data, you need to subclass EventArgs and then use that subclass (in the example they use MyEventArgs). EventArgs itself has no properties to hold data.

Upvotes: 1

Matthew
Matthew

Reputation: 25763

From the code, the generic type parameter in constrained by EventArgs (where TEventArgs : EventArgs). This means this is the most basic type the the EventHandler delgate supports.

When calling your event handler, can you just send null instead of an EventArgs instance?

As for why, I'm not sure why they require all events to have arguments, probably seemed like a good idea at the time.

One reason why they require EventArgs is because (before generics) the EventHandler delegate required EventArgs, so it might be to preserve compatibility.

Upvotes: 0

Related Questions