Skip to main content

24. Delegates and Events in C#

Level: Guided

ℹ️ What You'll Learn
  • What a delegate is
  • Use Action
  • Use Func
  • What an event is
  • Subscribe to an event
  • Raise an event safely

Delegates and events are advanced compared to earlier topics.

But the idea is simple:

Delegate = stores a method
Event = notifies others when something happens

The Problem: Notify Many Places

When a student is enrolled, many things may happen:

  • Send welcome message
  • Create fee account
  • Generate ID card
  • Notify class teacher

We do not want enrollment code to directly know every action.

Events help notify other code.

Quick Definitions

  • Delegate - Variable that holds a method reference
  • Method reference - Address/pointer to a method
  • Action - Delegate for methods with no return value
  • Func - Delegate for methods that return a value
  • Event - Notification that something happened
  • Subscribe - Register to listen to an event
  • Raise - Trigger/fire an event
  • Callback - Method called when event happens
  • EventHandler - Method that reacts to event
  • Invoke - Execute a delegate method

Why Delegates and Events Matter

Real scenario: Student enrollment.

Without events (bad design):

Enroll(student)
-> SendWelcomeMessage()
-> CreateFeeAccount()
-> NotifyTeacher()
-> GenerateIdCard()

Enrollment code must know all actions!

With events (good design):

Enroll(student)
-> Raise StudentEnrolled event
-> Other code subscribes and reacts

Enrollment code doesn't know actions!

Key benefit: Loose coupling. Enrollment doesn't need to know about fees, ID cards, or notifications. Other code subscribes and handles them.


What is a Delegate?

A delegate is a variable that can hold a method reference.

Example with Action:

Action<string> printMessage = Console.WriteLine;

printMessage("Hello Sahasra");

Action<string> means:

Method takes string input and returns nothing.

Action

Use Action when method returns nothing.

Action<string> sendSms = message =>
{
Console.WriteLine($"SMS: {message}");
};

sendSms("Fees paid successfully.");

Func

Use Func when method returns a value.

Func<double, string> getResult = percentage =>
{
return percentage >= 35 ? "Pass" : "Fail";
};

string result = getResult(84.8);
Console.WriteLine(result);

Func<double, string> means:

Input is double.
Output is string.

What is an Event?

An event is a notification.

Example:

Student enrolled
-> send welcome message
-> create fee account
-> notify teacher

Simple Event Example

💻 Try It — Console App
💡 Paste into Program.cs and press F5⌥ GitHub
StudentService service = new StudentService();

service.StudentEnrolled += name =>
{
Console.WriteLine($"Welcome message sent to {name}");
};

service.StudentEnrolled += name =>
{
Console.WriteLine($"Fee account created for {name}");
};

service.EnrollStudent("Sahasra Kumar");

public class StudentService
{
public event Action<string>? StudentEnrolled;

public void EnrollStudent(string name)
{
Console.WriteLine($"Student enrolled: {name}");

StudentEnrolled?.Invoke(name);
}
}

Output:

Student enrolled: Sahasra Kumar
Welcome message sent to Sahasra Kumar
Fee account created for Sahasra Kumar

Understand the Event Code

public event Action<string>? StudentEnrolled;

This means:

Other code can subscribe to StudentEnrolled.
When event is raised, subscribers receive student name.

Raise event safely:

StudentEnrolled?.Invoke(name);

The ?. avoids error if nobody subscribed.

Delegate vs Event

ConceptMeaning
DelegateHolds a method reference
EventNotification built using delegate
ActionDelegate with no return value
FuncDelegate with return value

When You'll Use This in SMS

Events decouple SMS features.

Real SMS events:

StudentEnrolled -> send welcome, create fee account, assign class
PaymentReceived -> update fee balance, generate receipt, send SMS
ExamCompleted -> generate report, update transcript, notify student
MarkAdded -> calculate average, update class ranking, check eligibility
FeeDue -> send reminder, create notification, block exam access
AttendanceMarked -> check eligibility, update progress, alert guardian

Without events: Exam code must know about notifications, transcripts, and SMS sending.

With events: Exam code just marks completion, others subscribe and handle their jobs.

Real scenario:

// Exam code doesn't care who listens
examService.OnExamCompleted += generateReport;
examService.OnExamCompleted += notifyStudent;
examService.OnExamCompleted += updateTranscript;
examService.CompleteExam(examId);

// Each subscriber runs independently
// Exam code stays focused on exams only

Real impact: SMS has 20+ events. One change in enrollment doesn't break fees or ID cards. New features subscribe without changing enrollment code.


Try This Now

Run the student enrollment example above. Then experiment:

  1. Add third subscriber to StudentEnrolled event
  2. Raise event from EnrollStudent
  3. See all three messages print
  4. Create PaymentService with PaymentReceived event
  5. Subscribe multiple handlers (receipt, balance, SMS notification)

See how events let multiple code blocks react to one action.


ℹ️ Video Tutorial

Delegates and events explained: Action, Func, events, subscribing, raising, real SMS scenarios. Video coming soon. Subscribe to NexCoding YouTube for updates.


Common Mistakes

Mistake 1: Raising event without null check

Wrong:

StudentEnrolled(name);

Correct:

StudentEnrolled?.Invoke(name);

Mistake 2: Using events for simple direct calls

If only one method must run directly, call the method. Use events when multiple subscribers may react.

Mistake 3: Forgetting to subscribe

If nobody subscribes, event runs no extra action.

Best Practices

  1. Use Action for methods with no return value.
  2. Use Func for methods with return value.
  3. Use events for notifications.
  4. Raise events using ?.Invoke.
  5. Keep event names clear: StudentEnrolled, PaymentReceived.
  6. Do not overuse events in beginner code.

Practice Task

Create FeeService.

Event:

PaymentReceived

When payment is made:

  • Print payment accepted.
  • Raise event.
  • Subscriber prints receipt message.

Quick Revision

QuestionAnswer
What is delegate?Method reference
What is Action?Delegate with no return value
What is Func?Delegate with return value
What is event?Notification
How to raise event safely??.Invoke()

🎯 Q1: What is a delegate?

A delegate is a type-safe reference to a method. It allows storing or passing methods as values.

🎯 Q2: What is Action?

Action is a built-in delegate for methods that return nothing.

🎯 Q3: What is Func?

Func is a built-in delegate for methods that return a value.

🎯 Q4: What is an event?

An event is a notification mechanism. Subscribers listen and react when the event is raised.

🎯 Q5: Why use ?.Invoke for events?

It safely raises the event only if there are subscribers.


🤖Use AI to Learn Faster
⚠️ Important for beginners: Do NOT use AI to write your code yet. Type every example yourself. Your brain learns by doing, not by reading AI output. Use AI only to explain and quiz you — not to code for you. Once you have strong fundamentals, AI becomes a powerful productivity tool for repetitive tasks.

Use ChatGPT, Claude, or Copilot to go deeper on C# delegates and events. Try these prompts:

  • "Explain delegates and events with a school enrollment example"
  • "Give me 5 practice tasks for Action, Func, and events"
  • "Explain delegate vs event simply"
  • "Quiz me with 5 beginner questions about delegates and events"

💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.

Next Article

Async and Await ->

nexcoding.in