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.

public struct SomethingHappenedEventArgs {
    public string SomeArgument { get; set; }
}

public class SomeType {
    public EventHandler<SomethingHappenedEventArgs> SomethingHappened;
}

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.

- kc

Published 21 September 05 08:30 by kcwalina

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Robert Kozak said on September 21, 2005 11:03 PM:
Definitely sounds interesting. Please keep us up to date as you investigate this.

-- Robert
# Chris Nahr said on September 22, 2005 4:01 AM:
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.
# Eric W said on September 22, 2005 9:57 AM:
In what instances would using a struct make raising an event cheaper?
# Bill Wagner said on September 25, 2005 10:38 AM:
Personally, I think this change would be a bad idea. My full reasoning is at the above URL.

# kcwalina said on September 26, 2005 12:27 PM:
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.
# Tanveer Badar said on December 8, 2007 5:43 AM:

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.

Leave a Comment

(required) 
(optional)
(required) 

  
Enter Code Here: Required
Page view tracker