C# Reference ยท Classes and Object-Oriented Concepts
Events and event handlers in C#
Reference for C# events: the event keyword, the EventHandler<TEventArgs> pattern, raising safely with ?.Invoke, unsubscribing, custom accessors and memory leak pitfalls.
An event lets a class announce that something happened and lets other code subscribe to it without the class knowing who they are (the publisher/subscriber pattern). It is a delegate field with a safety layer: outside code can only add (+=) and remove (-=) handlers, while only the declaring class can raise the event or clear it.
The standard .NET pattern uses EventHandler<TEventArgs>: a handler takes the sender (object?) and an event-arguments object, and returns void. Events with no data use plain EventHandler and EventArgs.Empty.
public event EventHandler<string>? Changed;
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
public event EventHandler<MyArgs>? Happened; // field-like event public event Action<string> Message { add { } remove { } } // custom accessors public static event EventHandler? Static; // static event public abstract event EventHandler Changed; // in an interface or abstract class Happened += Handler; // subscribe Happened -= Handler; // unsubscribe Happened?.Invoke(this, args); // raise (inside the declaring type)
| Part | Description |
|---|---|
| Type | Must be a delegate type. By convention EventHandler or EventHandler<TEventArgs> with (object? sender, TEventArgs e). |
add / remove |
Accessors that change the handler list. A field-like event generates them with thread-safe, lock-free updates. |
| Raising | Only inside the declaring class (or from a derived class if you provide a protected raiser). |
| Event args | Derive from EventArgs (not required since .NET 5, any type works with EventHandler<T>). |
Errors: CS0070 ("The event 'B.E' can only appear on the left hand side of += or -= (except when used from within the type 'B')") when outside code raises or assigns it.
Usage notes
- Null-conditional raise.
Happened?.Invoke(this, e)reads the delegate once, so it is safe if another thread unsubscribes the last handler between the check and the call. - Handlers run synchronously, in subscription order, on the raising thread. A slow handler delays the publisher, and an exception in one handler stops the rest (second example).
- Unsubscribe to avoid leaks. The publisher holds a reference to every subscriber through the delegate. A long-lived publisher (a static event, a service) therefore keeps short-lived subscribers alive. Always
-=inDisposeor use weak events. - Lambdas are hard to remove.
-=needs an equal delegate; a new lambda is a different object. Keep the handler in a variable or a method if you will unsubscribe. - Event vs. delegate property. Use
eventfor notifications; use a plainFunc/Actionparameter or property for a single callback that you expect to be replaced. - Async handlers.
async voidhandlers cannot be awaited and swallow ordering; they are acceptable only for UI-style events. For awaitable notifications, expose aFunc<Task>list or use channels. - Interfaces can declare events, and implementers use a field-like event to satisfy them.
- Standard naming: past tense for after-the-fact (
Closed), present participle for before (Closing), and anOn<Name>raiser method.