Compartilhar via


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

Comments

  • Anonymous
    September 21, 2005
    Definitely sounds interesting. Please keep us up to date as you investigate this.

    -- Robert
  • Anonymous
    September 21, 2005
    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.
  • Anonymous
    September 22, 2005
    In what instances would using a struct make raising an event cheaper?
  • Anonymous
    September 25, 2005
    Personally, I think this change would be a bad idea. My full reasoning is at the above URL.

  • Anonymous
    September 26, 2005
    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.
  • Anonymous
    December 07, 2007
    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.