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.
| Delegate | Returns | Example |
|---|---|---|
| Func of T result | Yes | Func int, bool |
| Action of T | No | Action string |
| Predicate of T | bool | Predicate 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
- How is an event different from a public delegate field?
- What do Func and Action represent compared with a custom delegate?
- Why use the null conditional operator before invoking an event?
- Name two reasons to unsubscribe an event handler.
- 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
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- 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
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- 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
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids 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