Event declaration syntax in C Sharp (C#) - Time & Space Complexity
When we declare events in C#, it's important to know how the program handles these declarations as the code grows.
We want to understand how the time to declare and use events changes as the number of events or handlers increases.
Analyze the time complexity of the following event declaration and usage.
public class Button
{
public event EventHandler? Clicked;
public void OnClick()
{
Clicked?.Invoke(this, EventArgs.Empty);
}
}
This code declares an event named Clicked and invokes it when OnClick is called.
Look at what happens when the event is invoked.
- Primary operation: Invoking all subscribed event handlers.
- How many times: Once per subscribed handler each time
OnClickis called.
As the number of subscribed handlers grows, the time to invoke the event grows too.
| Number of Handlers (n) | Approx. Invocations |
|---|---|
| 10 | 10 calls to handlers |
| 100 | 100 calls to handlers |
| 1000 | 1000 calls to handlers |
Pattern observation: The time to invoke grows directly with the number of handlers.
Time Complexity: O(n)
This means the time to invoke the event grows linearly with the number of subscribed handlers.
[X] Wrong: "Invoking an event always takes the same time no matter how many handlers are subscribed."
[OK] Correct: Each subscribed handler is called one by one, so more handlers mean more calls and more time.
Understanding how event invocation time grows helps you write responsive programs and shows you know how C# events work under the hood.
What if we changed the event to use a custom delegate that calls multiple methods internally? How would the time complexity change?