Declare and unsubscribe a C# event
An event lets a publisher notify subscribers without exposing the ability to raise that notification. Use EventHandler<TEventArgs> for a conventional event carrying data.
Keep the subscriber's lifetime explicit. A publisher can retain a subscriber through its delegate until that handler is removed.
Run a complete example
Create a .NET console project and replace Program.cs:
var counter = new Counter();
EventHandler<CountChangedEventArgs> handler = (_, e) => Console.WriteLine(e.Value);
counter.Changed += handler;
counter.Increment();
counter.Changed -= handler;
counter.Increment();
public sealed class CountChangedEventArgs(int value) : EventArgs {
public int Value { get; } = value;
}
public sealed class Counter {
private int _value;
public event EventHandler<CountChangedEventArgs>? Changed;
public void Increment() {
_value++;
Changed?.Invoke(this, new CountChangedEventArgs(_value));
}
}
dotnet run prints 1 once. The second increment changes the counter but no longer invokes the removed subscriber.
Account for execution context
These handlers run synchronously on the thread that raises the event. Raising an event does not dispatch it to a UI thread or make it asynchronous. A handler exception propagates to the caller and can stop later handlers from running.
The null-conditional invocation avoids a separate null check, but it does not make _value thread-safe. Add synchronization where the publisher's state requires it. When subscribing with a lambda, retain that delegate if you need to remove it later. Writing a second identical-looking lambda creates a different subscription expression.
Official references

Author: Herman Schoenfeld