-
The CLI specification describes three accessors for events; add, remove, and raise. Currently C# only makes use of add and remove, even for events using the auto syntax which are able to be invoked with a public Action MyEvent; produces
The same is of course true for events with custom accessors. Additionally, if C# encounters an event with a raise accessor, it is ignored and exposed as the underlying method. I think it might be beneficial to add some type of support for raise accessors, even if that is limited to events with custom accessors only. Some hypothetical use cases for this: An event which is has subscriptions added and removed very frequently may benefit from being implemented as follows: private readonly List<Action> MyEventInvocationList = new();
public event Action MyEvent
{
add => MyEventInvocationList.Add(value);
remove => MyEventInvocationList.Remove(value);
raise => MyEventInvocationList.ForEach(action => action());
} An event in a performance critical code path that has very infrequent subscription changes could make use of expression trees or reflection.emit to "stitch" the methods together. While both of these are possible to implement without a raise accessor, the switch from the auto implemented event to the custom event is a breaking change, in stark contrast with the change of an auto property to a property with custom accessors. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
The purpose of a private readonly List<Action> MyEventInvocationList = new();
public event Action MyEvent
{
add => MyEventInvocationList.Add(value);
remove => MyEventInvocationList.Remove(value);
}
protected void OnMyEvent()
{
MyEventInvocationList.ForEach(action => action());
} |
Beta Was this translation helpful? Give feedback.
-
@Reinms What is the reason that you're using |
Beta Was this translation helpful? Give feedback.
The purpose of a
raise
accessor is to give external code the ability to raise the event, which is not considered good practice. Any custom code required to raise the event internal to the publisher can be just as easily managed by a custom method within the class and has never required an accessor or additional language features. The idiomatic C# approach has always been: