EventHandler delegate pattern in C Sharp (C#) - Time & Space Complexity
When using the EventHandler delegate pattern, it's important to understand how the program's work grows as more event subscribers are added.
We want to know how the time to notify all listeners changes when the number of subscribers increases.
Analyze the time complexity of the following code snippet.
public class Publisher
{
public event EventHandler? OnChange;
public void RaiseEvent()
{
OnChange?.Invoke(this, EventArgs.Empty);
}
}
This code defines a publisher that raises an event notifying all subscribed listeners.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Invoking each subscribed event handler in the delegate invocation list.
- How many times: Once for each subscriber registered to the event.
Each time the event is raised, the program calls every subscriber in order.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to subscribers |
| 100 | 100 calls to subscribers |
| 1000 | 1000 calls to subscribers |
Pattern observation: The number of calls grows directly with the number of subscribers.
Time Complexity: O(n)
This means the time to notify all listeners grows linearly as more subscribers join.
[X] Wrong: "Raising the event takes the same time no matter how many subscribers there are."
[OK] Correct: Each subscriber must be called one by one, so more subscribers mean more calls and more time.
Understanding how event notifications scale helps you write responsive and efficient programs that handle many listeners gracefully.
"What if the event handlers themselves raise other events? How would that affect the overall time complexity?"
Practice
EventHandler delegate in C#?Solution
Step 1: Understand what a delegate does
A delegate defines a method signature that can be used to call methods indirectly.Step 2: Connect delegate to event handling
TheEventHandlerdelegate specifically defines the signature for methods that handle events.Final Answer:
To define a method signature for handling events -> Option DQuick Check:
EventHandler defines event method signature = D [OK]
- Confusing EventHandler with threading
- Thinking EventHandler stores data
- Mixing EventHandler with string formatting
EventHandler delegate in a class?Solution
Step 1: Recall event declaration syntax
Events are declared with the keywordeventfollowed by the delegate type and event name.Step 2: Match correct syntax
public event EventHandler MyEvent;matches the correct pattern.Final Answer:
public event EventHandler MyEvent; -> Option AQuick Check:
Event declaration = event + delegate + name [OK]
- Placing 'event' after delegate type
- Adding parentheses after event name
- Using void instead of event keyword
using System;
class Program {
public static event EventHandler OnAction;
static void Main() {
OnAction += (sender, e) => Console.WriteLine("Action happened!");
OnAction?.Invoke(null, EventArgs.Empty);
}
}Solution
Step 1: Understand event subscription
The lambda expression subscribes a method that prints "Action happened!" to the eventOnAction.Step 2: Invoke the event safely
The event is invoked with?.Invoke, so it calls the subscribed method, printing the message.Final Answer:
Action happened! -> Option AQuick Check:
Subscribed event invoked prints message = A [OK]
- Forgetting to subscribe to the event
- Not using null-conditional operator causing errors
- Expecting no output without invocation
public class Button {
public event EventHandler Click;
public void SimulateClick() {
Click(null, EventArgs.Empty);
}
}Solution
Step 1: Check event invocation safety
Events can be null if no subscribers exist, so invoking without null check causes runtime error.Step 2: Correct usage
UseClick?.Invoke(this, EventArgs.Empty);to safely invoke the event.Final Answer:
Event should be checked for null before invoking -> Option CQuick Check:
Always check event for null before invoke [OK]
- Invoking event directly without null check
- Assuming sender cannot be null
- Making event handler static unnecessarily
EventHandler pattern?Solution
Step 1: Understand custom event data
To send extra info, create a class derived fromEventArgswith needed properties.Step 2: Use generic EventHandler with custom args
Declare event asEventHandler<YourArgs>to pass the custom data safely.Final Answer:
Create a class inheriting from EventArgs with a string property, then declare event as EventHandler<YourArgs> -> Option BQuick Check:
Custom EventArgs + EventHandler<T> = B [OK]
- Passing data via sender parameter
- Using Action delegate instead of EventHandler
- Ignoring event data when needed
Ready to prove it?
Pass the test and this pattern moves unknown
