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

Raising events safely in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Event Safety 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 invocation code?
Consider the following C# code that raises an event safely. What will be printed when OnDataReceived is called?
C Sharp (C#)
using System;

class Program
{
    public event EventHandler DataReceived;

    public void OnDataReceived()
    {
        EventHandler handler = DataReceived;
        if (handler != null)
        {
            handler(this, EventArgs.Empty);
        }
    }

    static void Main()
    {
        Program p = new Program();
        p.DataReceived += (s, e) => Console.WriteLine("Event triggered");
        p.OnDataReceived();
    }
}
AEvent triggered
BNo output
CNullReferenceException at runtime
DCompilation error due to event invocation
Attempts:
2 left
💡 Hint
Think about how the event is copied to a local variable before invocation.
❓ Predict Output
intermediate
2:00remaining
What happens if you invoke an event without null check?
What will happen when the following code runs?
C Sharp (C#)
using System;

class Program
{
    public event EventHandler DataReceived;

    public void OnDataReceived()
    {
        DataReceived(this, EventArgs.Empty);
    }

    static void Main()
    {
        Program p = new Program();
        p.OnDataReceived();
    }
}
AThrows NullReferenceException at runtime
BPrints 'Event triggered'
CCompilation error due to missing event handler
DNo output and no error
Attempts:
2 left
💡 Hint
What happens if you call an event with no subscribers?
🔧 Debug
advanced
2:00remaining
Identify the thread-safety issue in this event raising code
What is the problem with this code when raising events in a multithreaded environment?
C Sharp (C#)
using System;

class Program
{
    public event EventHandler DataReceived;

    public void OnDataReceived()
    {
        if (DataReceived != null)
        {
            DataReceived(this, EventArgs.Empty);
        }
    }
}
AThe event is invoked twice accidentally
BThe event can become null after the null check but before invocation, causing NullReferenceException
CThe event handler list is modified during invocation causing InvalidOperationException
DNo thread-safety issues present
Attempts:
2 left
💡 Hint
Consider what happens if another thread unsubscribes between the null check and invocation.
❓ Predict Output
advanced
2:00remaining
What is the output of this event invocation with multiple subscribers?
Given the code below, what will be printed when OnDataReceived is called?
C Sharp (C#)
using System;

class Program
{
    public event EventHandler DataReceived;

    public void OnDataReceived()
    {
        EventHandler handler = DataReceived;
        handler?.Invoke(this, EventArgs.Empty);
    }

    static void Main()
    {
        Program p = new Program();
        p.DataReceived += (s, e) => Console.WriteLine("First subscriber");
        p.DataReceived += (s, e) => Console.WriteLine("Second subscriber");
        p.OnDataReceived();
    }
}
AOnly First subscriber
BSecond subscriber\nFirst subscriber
CFirst subscriber\nSecond subscriber
DNo output
Attempts:
2 left
💡 Hint
Events call subscribers in the order they were added.
❓ Predict Output
expert
2:00remaining
What is the output and why? (Event with custom delegate and null propagation)
Analyze the code below. What will be the output when RaiseEvent is called?
C Sharp (C#)
using System;

class Program
{
    public delegate void CustomEventHandler(string message);
    public event CustomEventHandler? CustomEvent;

    public void RaiseEvent()
    {
        CustomEvent?.Invoke("Hello World");
    }

    static void Main()
    {
        Program p = new Program();
        CustomEventHandler handler = msg => Console.WriteLine($"Received: {msg}");
        p.CustomEvent += handler;
        p.RaiseEvent();

        p.CustomEvent -= handler;
        p.RaiseEvent();
    }
}
ACompilation error due to null assignment to event
B
Received: Hello World
Throws NullReferenceException on second call
C
No output
Throws NullReferenceException on second call
D
Received: Hello World
(no output on second call)
Attempts:
2 left
💡 Hint
Events with null propagation operator do not throw if no subscribers.

Practice

(1/5)
1. What is the main reason to raise events safely in C#?
easy
A. To automatically unsubscribe all handlers after raising
B. To avoid errors when no event handlers are attached
C. To allow multiple events to be raised simultaneously
D. To improve the speed of event invocation

Solution

  1. Step 1: Understand event raising basics

    Raising an event without handlers can cause a null reference error.
  2. Step 2: Identify the purpose of safe raising

    Safe raising checks if handlers exist before invoking to prevent errors.
  3. Final Answer:

    To avoid errors when no event handlers are attached -> Option B
  4. Quick Check:

    Safe event raising prevents null errors [OK]
Hint: Check for null handlers before invoking events [OK]
Common Mistakes:
  • Assuming events always have handlers
  • Not checking for null before invoking
  • Confusing event raising with event subscription
2. Which of the following is the correct syntax to raise an event safely using the null-conditional operator?
easy
A. MyEvent.Invoke(this, EventArgs.Empty);
B. if (MyEvent != null) MyEvent(this, EventArgs.Empty);
C. MyEvent?.Invoke(this, EventArgs.Empty);
D. MyEvent(this, EventArgs.Empty);

Solution

  1. Step 1: Recall null-conditional operator usage

    The ?. operator safely calls a method only if the delegate is not null.
  2. Step 2: Match syntax for safe event raising

    Using MyEvent?.Invoke(...) safely raises the event without null checks.
  3. Final Answer:

    MyEvent?.Invoke(this, EventArgs.Empty); -> Option C
  4. Quick Check:

    ?.Invoke is the safe call syntax [OK]
Hint: Use ?.Invoke to call events safely in one line [OK]
Common Mistakes:
  • Forgetting the ?. operator and causing null exceptions
  • Using Invoke without null checks
  • Using if-check but missing parentheses
3. What will be the output of the following code?
public class Publisher {
    public event EventHandler? MyEvent;
    public void Raise() {
        var handler = MyEvent;
        if (handler != null) handler(this, EventArgs.Empty);
        else Console.WriteLine("No subscribers");
    }
}

var pub = new Publisher();
pub.Raise();
medium
A. No subscribers
B. NullReferenceException
C. Event raised successfully
D. Compilation error

Solution

  1. Step 1: Analyze event subscription

    No handlers are attached to MyEvent before calling Raise.
  2. Step 2: Check event invocation logic

    Since handler is null, the else branch prints "No subscribers".
  3. Final Answer:

    No subscribers -> Option A
  4. Quick Check:

    No handlers means else branch runs [OK]
Hint: If no handlers, else branch prints message [OK]
Common Mistakes:
  • Expecting event to raise without subscribers
  • Assuming null check is unnecessary
  • Confusing event invocation with subscription
4. Identify the error in this event raising code:
public event EventHandler? MyEvent;

public void Raise() {
    if (MyEvent != null)
        MyEvent(this, EventArgs.Empty);
}
medium
A. Event should be invoked with Invoke() method
B. No error, code is safe
C. Missing null-conditional operator
D. Possible race condition if handlers change after null check

Solution

  1. Step 1: Understand event invocation timing

    Between null check and invocation, handlers can unsubscribe causing null reference.
  2. Step 2: Identify race condition risk

    Copying delegate to local variable avoids this race condition.
  3. Final Answer:

    Possible race condition if handlers change after null check -> Option D
  4. Quick Check:

    Null check alone is not thread-safe [OK]
Hint: Copy event delegate to local variable before invoking [OK]
Common Mistakes:
  • Ignoring race conditions in multithreaded code
  • Assuming null check guarantees safety
  • Thinking Invoke() method is mandatory
5. You want to raise an event safely and also log every time the event is raised. Which of the following is the best approach?
public event EventHandler? MyEvent;

public void Raise() {
    var handler = MyEvent;
    if (handler != null) {
        handler(this, EventArgs.Empty);
        Console.WriteLine("Event raised");
    } else {
        Console.WriteLine("No subscribers");
    }
}
hard
A. This code is correct and safely raises the event with logging
B. Logging should be done before invoking the event
C. Use MyEvent?.Invoke(this, EventArgs.Empty) without local copy
D. Remove null check and catch exceptions instead

Solution

  1. Step 1: Check safe event raising

    Copying MyEvent to handler ensures safe invocation without race conditions.
  2. Step 2: Verify logging placement

    Logging after invocation confirms event was raised; else logs no subscribers.
  3. Final Answer:

    This code is correct and safely raises the event with logging -> Option A
  4. Quick Check:

    Local copy + logging after invoke is best practice [OK]
Hint: Copy event, invoke, then log success [OK]
Common Mistakes:
  • Logging before event may mislead if event throws
  • Skipping local copy risks race conditions
  • Ignoring null checks causes exceptions
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