Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to C#
C# Delegates and Events Guide

C# Delegates and Events Guide

C#1,216 viewsBy Admin
c-sharpdelegatesevents

Delegates

A delegate is a type-safe function pointer — a variable that holds a reference to a method.

delegate int Operation(int a, int b);

Operation add = (a, b) => a + b;
Console.WriteLine(add(2, 3)); // 5

Func, Action, Predicate

Func<int, int, int> multiply = (a, b) => a * b; // returns value
Action<string> log = msg => Console.WriteLine(msg); // no return
Predicate<int> isEven = n => n % 2 == 0; // returns bool

Events

public class Button {
    public event Action Clicked;
    public void Press() => Clicked?.Invoke();
}

var btn = new Button();
btn.Clicked += () => Console.WriteLine("Clicked!");
btn.Press();

FAQs

Delegate vs event?

An event is a restricted delegate — subscribers can only add/remove handlers, not invoke or overwrite it. More in our C# section.

Why use Func/Action?

They're built-in generic delegates so you rarely need to declare your own.