Skip to content
Learn Netverks

Lesson

Step 23/36 64% through track

delegates-events

Delegates and events

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~2 min
Level
intermediate

This lesson

This lesson teaches Delegates and events: the syntax, patterns, and safety habits you need before advancing in C#.

Delegates and events power callbacks and UI patterns—LINQ itself is built on delegates.

You will apply Delegates and events in contexts like: .NET services, Unity games, and Windows-centric tooling.

Write C# with Console.WriteLine (top-level or Program), click Run on server—the dev runner uses dotnet build/run on a temp net8 project (requires .NET SDK; LEARNING_RUNNER_ENABLED=true).

When you can explain the previous lesson's ideas without copying starter code.

A delegate is a type-safe function pointer—references methods matching a signature. Events wrap delegates with publish/subscribe semantics so external code cannot invoke subscribers directly—core to UI and domain notifications before DI-heavy architectures.

Delegate and Action/Func

Action<string> log = msg => Console.WriteLine(msg);
Func<int, int, int> add = (a, b) => a + b;

Action and Func are built-in generic delegate types—prefer them over custom delegate declarations for simple cases.

Events

event EventHandler<int> ScoreChanged;
ScoreChanged?.Invoke(this, 100);

Only the declaring class raises events; outsiders subscribe with += and unsubscribe with -=.

Important interview questions and answers

  1. Q: Delegate vs event?
    A: Events restrict invocation to the owner type—prevent external callers from firing another class's callbacks.
  2. Q: Func vs Action?
    A: Func returns a value; Action returns void—both are delegate shortcuts.

Self-check

  1. What operator subscribes to an event?
  2. Why use ?. when invoking events?

Pitfall: Forgetting to unsubscribe from events causes memory leaks—always remove handlers when the subscriber outlives the publisher.

Interview prep

Delegate vs interface?

Delegates are type-safe function pointers—great for callbacks; interfaces define broader contracts with multiple members.

Event memory leaks?

Subscribers held by events prevent GC of the subscriber—unsubscribe when the subscriber outlives the publisher.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • Func vs Action?
  • Event vs delegate field?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump