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

Raising events safely in C Sharp (C#) - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare an event named OnChange.

C Sharp (C#)
public event EventHandler [1];
Drag options to blanks, or click blank then click option'
AEventChanged
BChanged
CChangeEvent
DOnChange
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different event name than declared.
Forgetting to declare the event type.
2fill in blank
medium

Complete the code to safely raise the event OnChange using a local copy.

C Sharp (C#)
var handler = [1];
if (handler != null)
{
    handler(this, EventArgs.Empty);
}
Drag options to blanks, or click blank then click option'
AOnChange
BHandler
ConChange
DChangeEvent
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different variable name than the event name.
Not checking for null before invoking the event.
3fill in blank
hard

Fix the error in the event invocation by completing the code.

C Sharp (C#)
OnChange[1](this, EventArgs.Empty);
Drag options to blanks, or click blank then click option'
A.Invoke
B()
C.Call
D.Raise
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to call the event like a method without .Invoke.
Using non-existent methods like .Raise or .Call.
4fill in blank
hard

Fill both blanks to create a method RaiseOnChange that safely raises the event.

C Sharp (C#)
protected virtual void RaiseOnChange()
{
    var handler = [1];
    if (handler [2] null)
        handler(this, EventArgs.Empty);
}
Drag options to blanks, or click blank then click option'
AOnChange
B==
C!=
DOnChanged
Attempts:
3 left
💡 Hint
Common Mistakes
Using == instead of != in the if condition.
Copying the wrong event name.
5fill in blank
hard

Fill all three blanks to raise the event with a custom EventArgs subclass MyEventArgs.

C Sharp (C#)
protected virtual void RaiseOnChange(MyEventArgs e)
{
    var handler = [1];
    if (handler != null)
        handler([2], [3]);
}
Drag options to blanks, or click blank then click option'
AOnChange
Bthis
Ce
DEventArgs.Empty
Attempts:
3 left
💡 Hint
Common Mistakes
Passing EventArgs.Empty instead of the custom e.
Not checking if the event is null before invoking.

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