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)
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.PS: Ironically, that was proposed by yourself (#7881).
In proper implementation of
ICommand
it is recommended to forwardCanExecuteChanged
events toCommandManager.RequerySuggested
. Sometimes It’s also nice to forward some events on your custom control to “inner” nested controls in your template.