0
0
C Sharp (C#)programming~5 mins

Event declaration syntax in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Event declaration syntax
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

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 OnClick is called.
How Execution Grows With Input

As the number of subscribed handlers grows, the time to invoke the event grows too.

Number of Handlers (n)Approx. Invocations
1010 calls to handlers
100100 calls to handlers
10001000 calls to handlers

Pattern observation: The time to invoke grows directly with the number of handlers.

Final Time Complexity

Time Complexity: O(n)

This means the time to invoke the event grows linearly with the number of subscribed handlers.

Common Mistake

[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.

Interview Connect

Understanding how event invocation time grows helps you write responsive programs and shows you know how C# events work under the hood.

Self-Check

What if we changed the event to use a custom delegate that calls multiple methods internally? How would the time complexity change?