C# delegates, events, and lambdas

A delegate is a type that represents a method with a given signature. Func<TArg, TResult> and Action<TArg> are generic delegates for functions that return a value and for functions that do not. A lambda expression, such as x => x * x, creates one in place. Functions passed as arguments make code flexible: a method can take a Func that decides how to compute something.

C#
using System;

class Button {
  public event Action<string> Clicked;

  public void Click(string user) {
    Clicked?.Invoke(user);
  }
}

class Program {
  static void Main() {
    Func<int, int> square = x => x * x;
    Func<int, int> addOne = x => x + 1;
    Func<int, int> squareThenAddOne = x => addOne(square(x));
    Console.WriteLine(square(5) + " " + squareThenAddOne(5));

    var button = new Button();
    int clicks = 0;
    Action<string> counter = user => clicks++;
    Action<string> greeter = user => Console.WriteLine("hello " + user);

    button.Clicked += counter;
    button.Clicked += greeter;
    button.Click("Ada");
    button.Clicked -= greeter;
    button.Click("Bo");
    Console.WriteLine("clicks: " + clicks);
  }
}
Read the full lesson