Bird
Raised Fist0
C Sharp (C#)programming~20 mins

EventHandler delegate pattern in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
EventHandler Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this event subscription code?

Consider the following C# code using the EventHandler delegate pattern. What will be printed when the program runs?

C Sharp (C#)
using System;

class Publisher
{
    public event EventHandler? OnChange;

    public void RaiseEvent()
    {
        OnChange?.Invoke(this, EventArgs.Empty);
    }
}

class Program
{
    static void Main()
    {
        Publisher pub = new Publisher();
        pub.OnChange += Handler1;
        pub.OnChange += Handler2;
        pub.RaiseEvent();
    }

    static void Handler1(object? sender, EventArgs e)
    {
        Console.WriteLine("Handler1 called");
    }

    static void Handler2(object? sender, EventArgs e)
    {
        Console.WriteLine("Handler2 called");
    }
}
ANo output
BHandler2 called\nHandler1 called
CHandler1 called
DHandler1 called\nHandler2 called
Attempts:
2 left
💡 Hint

Events call their subscribed handlers in the order they were added.

❓ Predict Output
intermediate
2:00remaining
What happens if no handlers are subscribed?

What is the output of this code when RaiseEvent is called but no handlers are subscribed?

C Sharp (C#)
using System;

class Publisher
{
    public event EventHandler? OnChange;

    public void RaiseEvent()
    {
        OnChange?.Invoke(this, EventArgs.Empty);
        Console.WriteLine("Event raised");
    }
}

class Program
{
    static void Main()
    {
        Publisher pub = new Publisher();
        pub.RaiseEvent();
    }
}
ANullReferenceException
BCompilation error
CEvent raised
DNo output
Attempts:
2 left
💡 Hint

The null-conditional operator ?. prevents errors if no handlers exist.

🔧 Debug
advanced
2:00remaining
Why does this event handler code cause a runtime error?

Examine this code. Why does it throw a NullReferenceException when RaiseEvent is called?

C Sharp (C#)
using System;

class Publisher
{
    public event EventHandler OnChange;

    public void RaiseEvent()
    {
        OnChange(this, EventArgs.Empty);
    }
}

class Program
{
    static void Main()
    {
        Publisher pub = new Publisher();
        pub.RaiseEvent();
    }
}
AThe event OnChange must be static to be invoked.
BThe event OnChange is null because no handlers are subscribed, so calling it causes NullReferenceException.
CThe event OnChange requires a custom delegate type, not EventHandler.
DThe RaiseEvent method must be async to call the event.
Attempts:
2 left
💡 Hint

Events are null if no handlers are attached. Calling a null delegate causes an error.

📝 Syntax
advanced
2:00remaining
Which option correctly declares an event using EventHandler?

Which of the following is the correct way to declare an event named OnChange using the EventHandler delegate?

Apublic event EventHandler OnChange;
Bpublic EventHandler OnChange();
Cpublic event void OnChange(EventHandler handler);
Dpublic delegate EventHandler OnChange;
Attempts:
2 left
💡 Hint

Events use the event keyword followed by the delegate type and event name.

🚀 Application
expert
3:00remaining
How many handlers are called and what is the output?

Given this code, how many handlers are called and what is the exact output?

C Sharp (C#)
using System;

class Publisher
{
    public event EventHandler? OnChange;

    public void RaiseEvent()
    {
        OnChange?.Invoke(this, EventArgs.Empty);
    }
}

class Program
{
    static void Main()
    {
        Publisher pub = new Publisher();
        pub.OnChange += Handler1;
        pub.OnChange += Handler2;
        pub.OnChange -= Handler1;
        pub.RaiseEvent();
    }

    static void Handler1(object? sender, EventArgs e)
    {
        Console.WriteLine("Handler1 called");
    }

    static void Handler2(object? sender, EventArgs e)
    {
        Console.WriteLine("Handler2 called");
    }
}
AOne handler called\nHandler2 called
BTwo handlers called\nHandler1 called\nHandler2 called
CNo handlers called\nNo output
DOne handler called\nHandler1 called
Attempts:
2 left
💡 Hint

Removing a handler unsubscribes it from the event.

Practice

(1/5)
1. What is the main purpose of the EventHandler delegate in C#?
easy
A. To format strings for output
B. To create a new thread for event processing
C. To store data in a dictionary
D. To define a method signature for handling events

Solution

  1. Step 1: Understand what a delegate does

    A delegate defines a method signature that can be used to call methods indirectly.
  2. Step 2: Connect delegate to event handling

    The EventHandler delegate specifically defines the signature for methods that handle events.
  3. Final Answer:

    To define a method signature for handling events -> Option D
  4. Quick Check:

    EventHandler defines event method signature = D [OK]
Hint: EventHandler defines how event methods look [OK]
Common Mistakes:
  • Confusing EventHandler with threading
  • Thinking EventHandler stores data
  • Mixing EventHandler with string formatting
2. Which of the following is the correct syntax to declare an event using the EventHandler delegate in a class?
easy
A. public event EventHandler MyEvent;
B. public EventHandler event MyEvent;
C. event public EventHandler MyEvent();
D. public void event EventHandler MyEvent;

Solution

  1. Step 1: Recall event declaration syntax

    Events are declared with the keyword event followed by the delegate type and event name.
  2. Step 2: Match correct syntax

    public event EventHandler MyEvent; matches the correct pattern.
  3. Final Answer:

    public event EventHandler MyEvent; -> Option A
  4. Quick Check:

    Event declaration = event + delegate + name [OK]
Hint: Remember: event keyword before delegate type [OK]
Common Mistakes:
  • Placing 'event' after delegate type
  • Adding parentheses after event name
  • Using void instead of event keyword
3. What will be the output of the following code?
using System;
class Program {
    public static event EventHandler OnAction;
    static void Main() {
        OnAction += (sender, e) => Console.WriteLine("Action happened!");
        OnAction?.Invoke(null, EventArgs.Empty);
    }
}
medium
A. Action happened!
B. No output
C. NullReferenceException
D. Compilation error

Solution

  1. Step 1: Understand event subscription

    The lambda expression subscribes a method that prints "Action happened!" to the event OnAction.
  2. Step 2: Invoke the event safely

    The event is invoked with ?.Invoke, so it calls the subscribed method, printing the message.
  3. Final Answer:

    Action happened! -> Option A
  4. Quick Check:

    Subscribed event invoked prints message = A [OK]
Hint: ?.Invoke calls event only if not null [OK]
Common Mistakes:
  • Forgetting to subscribe to the event
  • Not using null-conditional operator causing errors
  • Expecting no output without invocation
4. Identify the error in this event usage code:
public class Button {
    public event EventHandler Click;
    public void SimulateClick() {
        Click(null, EventArgs.Empty);
    }
}
medium
A. EventHandler delegate cannot use EventArgs.Empty
B. Event must be invoked with a sender object, not null
C. Event should be checked for null before invoking
D. SimulateClick method must be static

Solution

  1. Step 1: Check event invocation safety

    Events can be null if no subscribers exist, so invoking without null check causes runtime error.
  2. Step 2: Correct usage

    Use Click?.Invoke(this, EventArgs.Empty); to safely invoke the event.
  3. Final Answer:

    Event should be checked for null before invoking -> Option C
  4. Quick Check:

    Always check event for null before invoke [OK]
Hint: Use ?.Invoke to avoid null errors [OK]
Common Mistakes:
  • Invoking event directly without null check
  • Assuming sender cannot be null
  • Making event handler static unnecessarily
5. You want to create a custom event that sends a string message to subscribers. Which is the best way to define the event and its arguments using the EventHandler pattern?
hard
A. Declare event as EventHandler and send string directly as sender parameter
B. Create a class inheriting from EventArgs with a string property, then declare event as EventHandler<YourArgs>
C. Use Action<string> delegate instead of EventHandler for the event
D. Declare event as EventHandler and ignore sending any data

Solution

  1. Step 1: Understand custom event data

    To send extra info, create a class derived from EventArgs with needed properties.
  2. Step 2: Use generic EventHandler with custom args

    Declare event as EventHandler<YourArgs> to pass the custom data safely.
  3. Final Answer:

    Create a class inheriting from EventArgs with a string property, then declare event as EventHandler<YourArgs> -> Option B
  4. Quick Check:

    Custom EventArgs + EventHandler<T> = B [OK]
Hint: Use EventHandler<T> with custom EventArgs for extra data [OK]
Common Mistakes:
  • Passing data via sender parameter
  • Using Action delegate instead of EventHandler
  • Ignoring event data when needed
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard