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

Event-driven design pattern in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Event-Driven Mastery
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 example?

Consider this C# code where a class publishes an event and another class subscribes to it. What will be printed when TriggerEvent is called?

C Sharp (C#)
using System;

public class Publisher
{
    public event EventHandler? OnChange;

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

public class Subscriber
{
    public void Subscribe(Publisher pub)
    {
        pub.OnChange += HandleEvent;
    }

    private void HandleEvent(object? sender, EventArgs e)
    {
        Console.WriteLine("Event received!");
    }
}

public class Program
{
    public static void Main()
    {
        Publisher pub = new Publisher();
        Subscriber sub = new Subscriber();
        sub.Subscribe(pub);
        pub.TriggerEvent();
    }
}
ANullReferenceException at runtime
BEvent received!
CNo output
DCompilation error due to event handler
Attempts:
2 left
💡 Hint

Think about what happens when TriggerEvent calls OnChange?.Invoke and if any subscriber is attached.

🧠 Conceptual
intermediate
1:30remaining
Which statement best describes the event-driven design pattern?

Choose the best description of the event-driven design pattern in programming.

AA pattern that requires polling to check for changes in state continuously.
BA pattern where functions are called sequentially without any event notifications.
CA pattern where components communicate by sending and receiving events asynchronously.
DA pattern that only works with synchronous method calls and no callbacks.
Attempts:
2 left
💡 Hint

Think about how components react to changes or actions in event-driven systems.

🔧 Debug
advanced
2:00remaining
What error does this event code produce?

Examine the following C# code snippet. What error will occur when compiling or running it?

C Sharp (C#)
using System;

public class Publisher
{
    public event EventHandler OnChange;

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

public class Program
{
    public static void Main()
    {
        Publisher pub = new Publisher();
        pub.TriggerEvent();
    }
}
ANullReferenceException at runtime
BCompilation error: event must be invoked with ?. operator
CNo error, prints nothing
DInvalidOperationException at runtime
Attempts:
2 left
💡 Hint

Consider what happens if no subscriber is attached to the event and the event is invoked directly.

📝 Syntax
advanced
2:00remaining
Which option correctly declares and raises a custom event in C#?

Choose the correct code snippet that declares a custom event and raises it properly.

A
public event EventHandler MyEvent;

protected virtual void OnMyEvent()
{
    MyEvent?.Invoke(this, EventArgs.Empty);
}
B
public event EventHandler MyEvent;

protected void OnMyEvent()
{
    MyEvent.Invoke();
}
C
public event EventHandler MyEvent;

protected void OnMyEvent()
{
    MyEvent(this);
}
D
public EventHandler MyEvent;

protected void OnMyEvent()
{
    MyEvent(this, EventArgs.Empty);
}
Attempts:
2 left
💡 Hint

Remember that events should be declared with the event keyword and invoked safely.

🚀 Application
expert
2:30remaining
How many times will the event handler run in this scenario?

Given this C# code where the same handler is subscribed twice to an event, how many times will the handler run when the event is triggered once?

C Sharp (C#)
using System;

public class Publisher
{
    public event EventHandler? OnChange;

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

public class Program
{
    public static void Main()
    {
        Publisher pub = new Publisher();
        EventHandler handler = (sender, e) => Console.WriteLine("Handler called");
        pub.OnChange += handler;
        pub.OnChange += handler;
        pub.TriggerEvent();
    }
}
A1
BCompilation error due to duplicate subscription
C0
D2
Attempts:
2 left
💡 Hint

Think about what happens if the same method is added twice to an event's invocation list.

Practice

(1/5)
1. What is the main role of an event subscriber in the event-driven design pattern?
easy
A. To manage the program's user interface layout
B. To listen for events and respond when they occur
C. To store data for the program's use
D. To create and send events to other parts of the program

Solution

  1. Step 1: Understand the roles in event-driven design

    In event-driven design, publishers send events and subscribers listen for these events.
  2. 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.
  3. Final Answer:

    To listen for events and respond when they occur -> Option B
  4. Quick Check:

    Subscriber listens and reacts = D [OK]
Hint: Subscribers always listen and react to events [OK]
Common Mistakes:
  • Confusing subscriber with publisher
  • Thinking subscriber creates events
  • Assuming subscriber manages UI layout
2. Which of the following is the correct syntax to declare an event in C#?
easy
A. public void event MyEvent();
B. event public MyEvent EventHandler;
C. public event EventHandler MyEvent;
D. EventHandler public event MyEvent;

Solution

  1. Step 1: Recall event declaration syntax in C#

    Events are declared with the keyword 'event' followed by a delegate type, then the event name.
  2. Step 2: Check each option

    public event EventHandler MyEvent; matches the correct syntax: 'public event EventHandler MyEvent;'. Others have wrong order or keywords.
  3. Final Answer:

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

    Correct event declaration = B [OK]
Hint: Event declaration: 'public event DelegateType EventName;' [OK]
Common Mistakes:
  • Mixing method and event syntax
  • Wrong keyword order
  • Missing 'event' keyword
3. What will be the output of the following C# code?
using System;
class Program {
  public static event Action OnNotify;
  static void Main() {
    OnNotify += () => Console.WriteLine("Event triggered");
    OnNotify?.Invoke();
  }
}
medium
A. Event triggered
B. No output
C. Compilation error
D. Runtime exception

Solution

  1. 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().
  2. Step 2: Predict output

    Since OnNotify has a subscriber, invoking it calls the lambda, printing "Event triggered" to the console.
  3. Final Answer:

    Event triggered -> Option A
  4. Quick Check:

    Subscribed event invoked prints message = A [OK]
Hint: Subscribed event invocation prints output [OK]
Common Mistakes:
  • Ignoring null-conditional operator ?.Invoke()
  • Expecting no output without subscription
  • Confusing event with method call syntax
4. Identify the error in this C# event-driven code snippet:
public class Publisher {
  public event EventHandler OnChange;
  public void Raise() {
    OnChange();
  }
}
medium
A. OnChange event is invoked without checking for null
B. EventHandler delegate is not declared
C. Raise method should be static
D. Event should be private

Solution

  1. Step 1: Review event invocation rules

    Events can be null if no subscribers exist. Invoking without null check causes runtime error.
  2. Step 2: Identify the error in code

    OnChange() is called directly without checking if OnChange is null, risking NullReferenceException.
  3. Final Answer:

    OnChange event is invoked without checking for null -> Option A
  4. Quick Check:

    Invoke event safely with null check = C [OK]
Hint: Always check event for null before invoking [OK]
Common Mistakes:
  • Calling event without null check
  • Assuming event is never null
  • Misunderstanding event access modifiers
5. You want to design a system where multiple subscribers react differently to a button click event. Which approach best uses the event-driven pattern in C# to achieve this?
hard
A. Make subscribers poll the button state continuously in a loop
B. Create a list of methods and call them manually without events
C. Use a static method to handle all button clicks centrally
D. Declare a public event, let subscribers add their handlers, and invoke event on button click

Solution

  1. Step 1: Understand event-driven design for multiple subscribers

    Events allow multiple subscribers to register handlers that get called automatically when the event fires.
  2. 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.
  3. Final Answer:

    Declare a public event, let subscribers add their handlers, and invoke event on button click -> Option D
  4. Quick Check:

    Use events for multiple subscriber reactions = A [OK]
Hint: Use events to notify multiple subscribers automatically [OK]
Common Mistakes:
  • Manually calling subscriber methods instead of using events
  • Using polling instead of event notifications
  • Centralizing all logic in static methods
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