A delegate is a type-safe reference to a method. You can store it in a variable, pass it to another method and call it later. An event is a delegate field with restrictions: other classes can subscribe and unsubscribe, but only the class that declares the event can raise it.
Delegates
You rarely need to declare your own delegate type. The built-in Action (returns nothing) and Func (returns a value) generic delegates cover almost every signature:
Func<int, int, int> add = (a, b) => a + b;
Console.WriteLine(add(2, 3)); // 5
Action<string> print = Console.WriteLine;
print += text => Console.WriteLine(text.ToUpperInvariant());
print("hello");
// hello
// HELLO
The first line assigns a lambda. The second assigns an existing method, Console.WriteLine. The third uses += to add a second method to the same delegate: delegates are multicast, so calling print runs both methods in the order they were added.
Declaring your own delegate type is still useful when the name documents intent, or when a parameter needs ref, out or in, which Action and Func cannot express:
public delegate bool TryParser<T>(string text, out T value);
Events
Here is a class that raises an event whenever it shows a message, and a subscriber that listens for it:
var messenger = new Messenger();
messenger.MessageShown += PrintMessage;
messenger.Show("Hello");
messenger.MessageShown -= PrintMessage;
messenger.Show("Nobody is listening");
static void PrintMessage(object? sender, MessageEventArgs e)
=> Console.WriteLine($"A new message: {e.Message}");
public class MessageEventArgs(string message) : EventArgs
{
public string Message { get; } = message;
}
public class Messenger
{
public event EventHandler<MessageEventArgs>? MessageShown;
public void Show(string message)
{
// ... display the message, then tell subscribers
OnMessageShown(new MessageEventArgs(message));
}
protected virtual void OnMessageShown(MessageEventArgs e)
=> MessageShown?.Invoke(this, e);
}
Output:
A new message: Hello
The second message prints nothing, because the handler was removed before it was shown.
This follows the .NET conventions that other developers will expect:
- The event uses
EventHandler<TEventArgs>, so handlers receive the sender and an arguments object. Adding information later means adding a property toMessageEventArgs, not changing every handler’s signature. - The event is raised from a
protected virtualmethod namedOnplus the event name, so derived classes can hook in. MessageShown?.Invoke(...)reads the field once and does nothing when there are no subscribers. The older pattern,if (MessageShown != null) MessageShown(s);, has a race: another thread can unsubscribe the last handler between the check and the call, and you get aNullReferenceException.
Why the event keyword matters
Without event, MessageShown would be a public delegate field. Any outside code could then call messenger.MessageShown = null; and silently remove every other subscriber, or invoke messenger.MessageShown(...) and fake a message. The event keyword limits outside code to += and -=.
Traps
Forgotten subscriptions keep objects alive. The publisher’s delegate holds a reference to every subscriber. If a long-lived object (a static service, a main window) raises an event, short-lived subscribers will never be garbage collected until they unsubscribe. This is one of the most common memory leaks in .NET desktop apps.
You cannot unsubscribe an inline lambda. x.Changed += (s, e) => ...; followed by x.Changed -= (s, e) => ...; removes nothing, because the second lambda is a different delegate instance. Store the handler in a variable or use a named method if you need to remove it.
One failing handler stops the rest. If a handler throws, the exception propagates out of Invoke and the remaining handlers never run. If that matters, loop over GetInvocationList() and call each handler inside its own try block.
Handlers run on the raising thread. If a background thread raises the event, a WinForms or WPF handler that touches controls must marshal back to the UI thread.
async void handlers. Event handlers are the one place where async void is acceptable, but the publisher cannot await them and does not see their exceptions.