MSDN .NET Documentation

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:

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

See Also