24. Delegates and Events in C#
Level: Guided
- 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
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
| Concept | Meaning |
|---|---|
| Delegate | Holds a method reference |
| Event | Notification built using delegate |
| Action | Delegate with no return value |
| Func | Delegate 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:
- Add third subscriber to StudentEnrolled event
- Raise event from EnrollStudent
- See all three messages print
- Create PaymentService with PaymentReceived event
- Subscribe multiple handlers (receipt, balance, SMS notification)
See how events let multiple code blocks react to one action.
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
- Use
Actionfor methods with no return value. - Use
Funcfor methods with return value. - Use events for notifications.
- Raise events using
?.Invoke. - Keep event names clear:
StudentEnrolled,PaymentReceived. - 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
| Question | Answer |
|---|---|
| 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() |
A delegate is a type-safe reference to a method. It allows storing or passing methods as values.
Action is a built-in delegate for methods that return nothing.
Func is a built-in delegate for methods that return a value.
An event is a notification mechanism. Subscribers listen and react when the event is raised.
It safely raises the event only if there are subscribers.
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.