0Pricing
C# Academy · Lesson

Events: publish/subscribe, event keyword

Publish/subscribe with events: declare event, add/remove handlers, pass data via EventArgs, and raise with the OnX pattern.

Events overview

Goal: Publish/subscribe with events.

  • Declare an event on the publisher
  • Subscribe with +=, unsubscribe with -=
  • Raise safely in the publisher
  • Pass data using EventArgs

Basic event usage

Expose an event and let listeners attach/detach. Only the publisher invokes it.

using System;

public class Button
{
  public event EventHandler Click;

  public void SimulateClick()
  {
    // Safe raise: copy then invoke if not null (C# 6-safe)
    EventHandler h = Click;
    if (h != null) h(this, EventArgs.Empty);
  }
}

public class Program
{
  static void OnClick(object sender, EventArgs e)
  {
    Console.WriteLine("Clicked!");
  }

  public static void Main(string[] args)
  {
    Button b = new Button();
    b.Click += OnClick;    // subscribe
    b.SimulateClick();     // prints "Clicked!"

    b.Click -= OnClick;    // unsubscribe
    b.SimulateClick();     // no output
  }
}

All lessons in this course

  1. delegate, Action/Func, closures
  2. Events: publish/subscribe, event keyword
  3. Event patterns, pitfalls (memory leaks)
← Back to C# Academy