Overview
An event
in .NET provides a way for a class or object to notify other classes or objects when something of interest occurs. Events are based on delegates and follow the observer pattern.
Syntax
public event EventHandler<TEventArgs> EventName;
Common patterns:
EventHandler
– no event data.EventHandler<TEventArgs>
– provides typed event data.
Example
The following example demonstrates a simple timer that raises a Tick
event every second.
using System;
using System.Timers;
public class SimpleTimer
{
private readonly Timer _timer;
public event EventHandler<ElapsedEventArgs> Tick;
public SimpleTimer(double interval)
{
_timer = new Timer(interval);
_timer.Elapsed += OnTimerElapsed;
}
public void Start() => _timer.Start();
public void Stop() => _timer.Stop();
private void OnTimerElapsed(object sender, ElapsedEventArgs e)
{
Tick?.Invoke(this, e);
}
}
// Consumer
class Program
{
static void Main()
{
var timer = new SimpleTimer(1000);
timer.Tick += Timer_Tick;
timer.Start();
Console.WriteLine("Press Enter to exit...");
Console.ReadLine();
}
private static void Timer_Tick(object sender, ElapsedEventArgs e)
{
Console.WriteLine($"Tick at {e.SignalTime:HH:mm:ss}");
}
}
Remarks
- Events are multicast delegates – multiple handlers can be attached.
- Use the
?.
null‑conditional operator when raising events to avoidNullReferenceException
. - Follow the naming convention: verbs or verb phrases (e.g.,
Clicked
,DataReceived
). - Prefer
protected virtual void OnEventName(...)
pattern for derived classes to override.