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

Raising events safely in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style10 modes available
Raising events safely
📖 Scenario: Imagine you are building a simple notification system where a class sends messages to subscribers when something important happens.
🎯 Goal: You will create a class with an event, set up a subscriber method, and raise the event safely to notify subscribers without errors.
📋 What You'll Learn
Create a delegate type called NotifyEventHandler that takes object sender and EventArgs e parameters
Create a class called Notifier with an event called OnNotify of type NotifyEventHandler
Write a method RaiseNotification in Notifier that raises OnNotify safely using a local copy
Create a subscriber method called HandleNotification that prints a message when notified
Subscribe HandleNotification to the OnNotify event
Call RaiseNotification to trigger the event and display the message
💡 Why This Matters
🌍 Real World
Events are used in user interfaces, messaging systems, and many applications to notify parts of a program when something happens.
💼 Career
Understanding how to raise events safely is important for writing reliable and thread-safe C# applications, a common requirement in software development jobs.
Progress0 / 4 steps
1
Create the delegate and Notifier class with event
Create a delegate called NotifyEventHandler that takes object sender and EventArgs e. Then create a class called Notifier with an event OnNotify of type NotifyEventHandler.
C Sharp (C#)
Hint

Delegates define the shape of methods that can be called. Events use delegates to notify subscribers.

2
Add the RaiseNotification method with safe event raising
Inside the Notifier class, add a method called RaiseNotification that creates a local copy of OnNotify and invokes it with this and EventArgs.Empty if the copy is not null.
C Sharp (C#)
Hint

Copy the event delegate to a local variable to avoid race conditions when raising events.

3
Create a subscriber method and subscribe to the event
Outside the Notifier class, create a method called HandleNotification that takes object sender and EventArgs e and prints "Notification received!". Then create a Notifier object called notifier and subscribe HandleNotification to notifier.OnNotify.
C Sharp (C#)
Hint

Subscriber methods must match the delegate signature. Use += to subscribe to events.

4
Call RaiseNotification to trigger the event and print the message
In the Main method, after subscribing HandleNotification to notifier.OnNotify, call notifier.RaiseNotification() to raise the event and display the message.
C Sharp (C#)
Hint

Calling the method that raises the event will notify all subscribers and print the message.

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