🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

C# Delegates, Events, and EventHandler — Complete Beginner Guide

C# FundamentalsDelegates and Events🟢 Free Lesson

C# Delegates, Events, and EventHandler — Complete Beginner Guide

Learning Objectives

  • Create and invoke delegates
  • Pass methods as callbacks
  • Declare and raise events
  • Subscribe with EventHandler
  • Design loosely coupled component communication

What Is a Delegate

A delegate is a type safe reference to a method. It lets you store a method in a variable, pass it as an argument, and invoke it later without knowing the exact method name at compile time of the call site.

delegate int MathOp(int a, int b);

class Program
{
    static int Add(int a, int b) => a + b;
    static int Multiply(int a, int b) => a * b;

    static void Main()
    {
        MathOp op = Add;
        Console.WriteLine(op(2, 3));

        op = Multiply;
        Console.WriteLine(op(2, 3));
    }
}

The delegate signature must match the methods you assign.

Built-in Generic Delegates

You rarely need custom delegate types. Func and Action cover most cases.

DelegateReturnsExample
Func of T resultYesFunc int, bool
Action of TNoAction string
Predicate of TboolPredicate int
Func<int, int, int> add = (a, b) => a + b;
Action<string> print = msg => Console.WriteLine(msg);

print("Start");
Console.WriteLine(add(4, 5));

Lambdas keep callback code short and readable.

Method Groups and Lambdas

void Whisper(string text)
{
    Console.WriteLine(text.ToLower());
}

Action<string> shout = t => Console.WriteLine(t.ToUpper());
Action<string> speak = Whisper;

shout("Hello");
speak("Hello");

You can assign a named method group or an inline lambda to a compatible delegate.

Multicast Delegates

Delegates can hold more than one method. Invoking runs each in subscription order.

Action pipeline = () => Console.WriteLine("Step 1");
pipeline += () => Console.WriteLine("Step 2");
pipeline += () => Console.WriteLine("Step 3");

pipeline();

What Is an Event

An event is a special member built on delegates. It lets publishers announce that something happened while controlling who can raise it. Only the declaring type can invoke the event directly; outside code can subscribe or unsubscribe.

class Logger
{
    public event Action OnLog;

    public void Write(string message)
    {
        Console.WriteLine(message);
        OnLog?.Invoke();
    }
}

Logger logger = new Logger();
logger.OnLog += () => Console.WriteLine("Notified");
logger.Write("File saved");

The null conditional operator safely invokes only when subscribers exist.

EventHandler and EventArgs

For richer messages, use EventHandler with EventArgs.

class OrderService
{
    public event EventHandler OrderPlaced;

    public void PlaceOrder(string item)
    {
        Console.WriteLine("Order placed: " + item);
        OrderPlaced?.Invoke(this, EventArgs.Empty);
    }
}

class EmailNotifier
{
    public void Subscribe(OrderService service)
    {
        service.OrderPlaced += Handle;
    }

    private void Handle(object sender, EventArgs e)
    {
        Console.WriteLine("Sending confirmation email");
    }
}

OrderService service = new OrderService();
EmailNotifier notifier = new EmailNotifier();
notifier.Subscribe(service);
service.PlaceOrder("Keyboard");

Custom event args

class DownloadEventArgs : EventArgs
{
    public string FileName { get; init; }
    public double Percent { get; init; }
}

class Downloader
{
    public event EventHandler Progress;

    public void Simulate()
    {
        Progress?.Invoke(this, new DownloadEventArgs
        {
            FileName = "video.mp4",
            Percent = 50
        });
    }
}

Downloader d = new Downloader();
d.Progress += (s, e) => Console.WriteLine(e.FileName + " " + e.Percent);
d.Simulate();

Subscribe and Unsubscribe

void Handler(object s, EventArgs e)
{
    Console.WriteLine("Handled");
}

OrderService svc = new OrderService();
svc.OrderPlaced += Handler;
svc.PlaceOrder("Mouse");
svc.OrderPlaced -= Handler;
svc.PlaceOrder("Keyboard");

Always unsubscribe long lived subscriptions to avoid memory leaks.

Design Benefits

  • Components collaborate without hard dependencies
  • Multiple listeners can react to one fact
  • Publishers stay unaware of concrete subscribers
  • Testing becomes easier with fake handlers

Common Mistakes

Forgetting to unsubscribe

Static or long living subscribers can keep objects alive longer than intended.

Invoking events from outside the owner

events restrict external invocation on purpose. Raise them only inside the declaring class.

Doing heavy work synchronously in handlers

Long handler logic delays the publisher. Queue slow work when performance matters.

Key Takeaways

💡

  • Delegates are type safe method references and support multicast
  • Func and Action cover most callback signatures without custom types
  • events restrict raising to the owner while allowing public subscription
  • EventHandler with EventArgs carries structured notification data
  • Pair every long lived subscription with an unsubscribe path

Practice Questions

  1. How is an event different from a public delegate field?
  2. What do Func and Action represent compared with a custom delegate?
  3. Why use the null conditional operator before invoking an event?
  4. Name two reasons to unsubscribe an event handler.
  5. Build a simple ThresholdReached event that fires when a counter hits ten, and handle it from outside the class.

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert C# Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement