Lesson 45 +10 XP

Delegates & Events

Delegates & Events

Delegates

A delegate is a type that holds a reference to a method - a "method pointer" with type safety.

delegate int MyDelegate(int a, int b);

static int Add(int x, int y) { return x + y; }

MyDelegate d = Add;
Console.WriteLine(d(3, 4));   // 7

The delegate MyDelegate can point to any method that takes two ints and returns an int.

Multicast delegates

A delegate can hold several methods and call them all:

delegate void Greeting(string name);

void Hello(string n) => Console.WriteLine("Hello, " + n);
void Bye(string n) => Console.WriteLine("Bye, " + n);

Greeting g = Hello;
g += Bye;
g("Ada");   // Hello, Ada / Bye, Ada

Events

An event is a way for a class to notify other code when something happens. It's based on delegates, but only the class can raise the event:

public event EventHandler TimerFired;

// other code subscribes: timer.TimerFired += HandleFired;

Events power GUIs ("button clicked"), async callbacks, and more.

Action and Func

Modern C# provides built-in delegates:

  • Action<T> - a method that returns nothing.
  • Func<T, TResult> - a method that returns a value.
Func<int, int, int> add = (a, b) => a + b;
Action<string> print = s => Console.WriteLine(s);

TL;DR

  • A delegate references a method with type safety.
  • Delegates can hold multiple methods (multicast).
  • Events let classes notify other code.
  • Action and Func are built-in delegate types.