Delegates, Events, and Func/Action

Intermediate Updated March 21, 2025

🧭 Delegates, Events, and Func/Action

🔹 What is a Delegate?

delegate int MathOperation(int x, int y);

int Add(int a, int b) => a + b;

MathOperation op = Add;
Console.WriteLine(op(3, 4));  // Output: 7

🔹 Built-in Delegates: Action, Func, Predicate

Func<int, int, int> multiply = (a, b) => a * b;
Action<string> greet = name => Console.WriteLine($"Hello, {name}");
Predicate<int> isEven = x => x % 2 == 0;

🔹 Event Handling Pattern

public class Button
{
    public event EventHandler Clicked;

    public void Click()
    {
        if (Clicked != null)
            Clicked(this, EventArgs.Empty);
    }
}