Value Type EventArgs

I just wanted to blog about some interesting API design discussion we had recently. We discussed whether to relax the event design guidelines to allow value type “event args.” This would make raising some events cheaper.

One implication of such change is that EventHandler<T> would have to be modified. Today T is constrained to EventArgs and the SomethingHappenedEventArgs struct cannot inherit from EventArgs. The solution is to either remove the constraint from T or to add a marker interface IEventArgs, implement it on EventArgs, and change the constraint to IEventArgs. This of course won’t happen in Whidbey (way too late) and in general I am not yet convinced the change is worth the trouble; it needs to be investigated more.

Will you keep the non-struct EventArgs, though? It’s occasionally useful to have a small hierarchy of EventArgs classes, and vary the event handler response depending on which type was delivered.

Having struct-type EventArgs sounds good in principle but I’m not sure they would be a big gain overall. Many events are fired with EventArgs.Empty anyway, and that’s just a constant reference without any allocation.

Chris, we would of course keep EventArgs. Removing it would be a breaking change.

Eric, we discovered some events in WinFx that are raised very often and cannot use shared .Empty instance. Using a struct would save us allocating memory on the heap.

Bill, we found real scenarios which would be 1-2% faster with struct event args. The event args never get promoted, yet there is so many of them that they stress the collector. But I agree with you that the gains may be too small to justify the drawbacks.

There is no point making EventArgs a value type. I want my methods to be inlined. JIT at the moment simply refuses to inline methods with value type arguments. Bugs are even filed on connect about this issue.