WeCodeAcademy

C# Delegates, Events and Lambdas

A delegate is a type that holds a method. Func and Action are ready-made generic delegates. An event lets objects announce that something happened.

ExampleC#
using System;

class Button
{
    public event Action<string> Clicked;

    public void Click(string who)
    {
        if (Clicked != null) Clicked(who);
    }
}

class Program
{
    static void Main()
    {
        Func<int, int> square = x => x * x;
        Func<int, int, int> add = (a, b) => a + b;
        Action<string> hello = name => Console.WriteLine("Hello, " + name);

        Console.WriteLine(square(7));
        Console.WriteLine(add(2, 3));
        hello("Ada");

        Button b = new Button();
        b.Clicked += who => Console.WriteLine(who + " clicked");
        b.Clicked += who => Console.WriteLine("logged " + who);
        b.Click("Sam");
    }
}
Output
49
5
Hello, Ada
Sam clicked
logged Sam
Quick check

What does Func<int, int> describe?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.