Event-driven design pattern in C Sharp (C#) - Time & Space Complexity
When using the event-driven design pattern, it's important to understand how the program's work grows as more events happen.
We want to see how the number of events affects the time the program takes to respond.
Analyze the time complexity of the following code snippet.
public class Publisher
{
public event Action? OnChange;
public void RaiseEvent()
{
OnChange?.Invoke();
}
}
public class Subscriber
{
public void Respond() { /* handle event */ }
}
This code shows a publisher that raises an event and subscribers that respond when the event happens.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Invoking all subscriber methods when the event is raised.
- How many times: Once per event raised, calling each subscriber's response method.
Each time the event is raised, the program calls every subscriber's response method.
| Input Size (n subscribers) | Approx. Operations per Event |
|---|---|
| 10 | 10 calls |
| 100 | 100 calls |
| 1000 | 1000 calls |
Pattern observation: The work grows directly with the number of subscribers.
Time Complexity: O(n)
This means the time to handle an event grows linearly with the number of subscribers listening.
[X] Wrong: "Raising an event always takes the same time no matter how many subscribers there are."
[OK] Correct: Each subscriber adds work because the event calls their method, so more subscribers mean more calls and more time.
Understanding how event handling scales helps you design responsive programs and shows you can think about performance in real situations.
"What if the event had to notify subscribers in a nested way, where each subscriber triggers another event? How would the time complexity change?"
Practice
Solution
Step 1: Understand the roles in event-driven design
In event-driven design, publishers send events and subscribers listen for these events.Step 2: Identify subscriber's responsibility
The subscriber's job is to react or respond when an event happens, meaning it listens and acts accordingly.Final Answer:
To listen for events and respond when they occur -> Option BQuick Check:
Subscriber listens and reacts = D [OK]
- Confusing subscriber with publisher
- Thinking subscriber creates events
- Assuming subscriber manages UI layout
Solution
Step 1: Recall event declaration syntax in C#
Events are declared with the keyword 'event' followed by a delegate type, then the event name.Step 2: Check each option
public event EventHandler MyEvent; matches the correct syntax: 'public event EventHandler MyEvent;'. Others have wrong order or keywords.Final Answer:
public event EventHandler MyEvent; -> Option CQuick Check:
Correct event declaration = B [OK]
- Mixing method and event syntax
- Wrong keyword order
- Missing 'event' keyword
using System;
class Program {
public static event Action OnNotify;
static void Main() {
OnNotify += () => Console.WriteLine("Event triggered");
OnNotify?.Invoke();
}
}Solution
Step 1: Understand event subscription and invocation
The event OnNotify is subscribed with a lambda that prints "Event triggered". The event is then invoked safely with ?.Invoke().Step 2: Predict output
Since OnNotify has a subscriber, invoking it calls the lambda, printing "Event triggered" to the console.Final Answer:
Event triggered -> Option AQuick Check:
Subscribed event invoked prints message = A [OK]
- Ignoring null-conditional operator ?.Invoke()
- Expecting no output without subscription
- Confusing event with method call syntax
public class Publisher {
public event EventHandler OnChange;
public void Raise() {
OnChange();
}
}Solution
Step 1: Review event invocation rules
Events can be null if no subscribers exist. Invoking without null check causes runtime error.Step 2: Identify the error in code
OnChange() is called directly without checking if OnChange is null, risking NullReferenceException.Final Answer:
OnChange event is invoked without checking for null -> Option AQuick Check:
Invoke event safely with null check = C [OK]
- Calling event without null check
- Assuming event is never null
- Misunderstanding event access modifiers
Solution
Step 1: Understand event-driven design for multiple subscribers
Events allow multiple subscribers to register handlers that get called automatically when the event fires.Step 2: Evaluate options for best practice
Declare a public event, let subscribers add their handlers, and invoke event on button click uses a public event and lets subscribers add handlers, which is the standard event-driven approach. Others are less efficient or not event-driven.Final Answer:
Declare a public event, let subscribers add their handlers, and invoke event on button click -> Option DQuick Check:
Use events for multiple subscriber reactions = A [OK]
- Manually calling subscriber methods instead of using events
- Using polling instead of event notifications
- Centralizing all logic in static methods
Ready to prove it?
Pass the test and this pattern moves unknown
