roslyn: Proposal: Expression-bodied events

There are two common use cases where you actually need to write add and remove manually: Explicit implementations and forwarding events to each other.

class C : Interface {
  private EventHandler @event;
  event EventHandler Interface.Event {
     add { @event += value; }
     remove { @event -= value; }
  }
  public event EventHandler Event {
    add { obj.Event += value; }
    remove { obj.Event -= value; }
  }
}

This can be a source of bugs like using += in remove and these seem to be complete boilerplate which auto events are meant to prevent. It’d be nice to be able to define these events to be auto implemented,

class C : Interface {
  private EventHandler @event;
  event EventHandler Interface.Event => @event;
  public event EventHandler Event => obj.Event;
}

The expression in front of => must be a valid lvalue. Related: #1276.

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 4
  • Comments: 15 (8 by maintainers)

Most upvoted comments

I’m talking about consistency. I don’t see myself writing expression-bodied ctors or dtors either, but here we are. You’re right about its semantics, I’ll wait for the team to decide whether it’s a good idea or not, conciseness is quite nice, though.

@MgSam This is a part of the language anyways (without any particular replacement like delegate vs lambda). I don’t agree that they are less useful or deprecated, a lot of “modern” frameworks depend on this, because it’s idiomatic C# and has proper support in CLR. Also, they can be resurrected through observable interop to be more useful in a wide variety of use cases.

Since => is being considered for other constructs as well (per @gafter’s comment), it’d be nice to also support it for events.

public class Foo : IFoo {
    private Handler @event;
    event Handler IFoo.Event => @event;
}

PS: Ironically, that was proposed by yourself (#7881).

What about WPF makes it necessary to explicitly implement or forward events?

In proper implementation of ICommand it is recommended to forward CanExecuteChanged events to CommandManager.RequerySuggested. Sometimes It’s also nice to forward some events on your custom control to “inner” nested controls in your template.