C# Reference ยท Keywords and Statements
The event keyword
Reference for the C# event keyword: declare events with EventHandler, raise them safely, subscribe and unsubscribe, and avoid memory leaks.
An event lets an object announce that something happened, so other objects can react without the publisher knowing who they are. It is the publish/subscribe pattern built into the language. An event is a delegate field with restricted access: outside code can only subscribe (+=) or unsubscribe (-=); only the declaring class can raise it or reset it.
The standard shape uses EventHandler or EventHandler<TEventArgs>: a method with a sender object and an event-data object. Raise an event with the null-conditional operator so that nothing happens when there are no subscribers.
public event EventHandler? Finished; protected void OnFinished() => Finished?.Invoke(this, EventArgs.Empty);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
[modifiers] event DelegateType Name; // field-like event [modifiers] event DelegateType Name { add { ... } remove { ... } } // custom accessors obj.Name += handler; obj.Name -= handler; Name?.Invoke(sender, args); // inside the declaring type
Events can be static, virtual, abstract or declared in interfaces. EventHandler<TEventArgs> has the signature void (object? sender, TEventArgs e); since .NET Core 2.0 TEventArgs no longer has to derive from EventArgs.
Errors: outside the declaring type you cannot call or assign an event (CS0070). Raising with Name() instead of Name?.Invoke() throws NullReferenceException when nobody subscribed.
Usage notes
- Raise safely:
Handler?.Invoke(...)reads the field once, so a handler removed on another thread does not cause a null reference. - Exceptions in a handler stop the remaining handlers. Wrap them or iterate
GetInvocationList()if every subscriber must run. - Memory leaks: a subscription keeps the subscriber alive as long as the publisher is alive. Unsubscribe in
Disposeor use a weak-event pattern for long-lived publishers. - Order: handlers run in subscription order, synchronously, on the raising thread.
- Naming: past tense for after-the-fact events (
Closed),-ingfor events before (Closing), plus a protected virtualOnXxxmethod that raises them. - Async handlers:
async voidhandlers are fine for events but their exceptions cannot be caught by the publisher. - Field-like events are thread-safe for add/remove in modern compilers.
Related
kw-delegate,op-lambda,kw-async-await- Tutorials: Events, Delegates