Recall & Review
beginner
What does it mean to raise events safely in C#?
Raising events safely means checking if there are any subscribers before invoking the event to avoid null reference errors.
Click to reveal answer
intermediate
Why should you copy the event delegate to a local variable before raising it?
Copying the event delegate to a local variable prevents race conditions where subscribers might unsubscribe between the null check and the event invocation.
Click to reveal answer
beginner
Show a simple safe way to raise an event named
MyEvent in C#.var handler = MyEvent;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
Click to reveal answer
beginner
What can happen if you raise an event without checking for null?
If no subscribers exist, the event delegate is null and invoking it causes a NullReferenceException, crashing the program.
Click to reveal answer
intermediate
How does the null-conditional operator simplify raising events safely in modern C#?
You can write
MyEvent?.Invoke(this, EventArgs.Empty); which automatically checks for null before invoking the event.Click to reveal answer
What is the main reason to check if an event is null before raising it?
✗ Incorrect
Checking for null ensures the event has subscribers, preventing a NullReferenceException when invoking it.
Which of these is the safest way to raise an event in C#?
✗ Incorrect
Copying the event delegate to a local variable avoids race conditions and null reference errors.
What does the null-conditional operator (?.) do when raising events?
✗ Incorrect
The ?. operator checks if the event is null and only invokes it if there are subscribers.
What problem can occur if you raise an event directly without a null check in a multi-threaded environment?
✗ Incorrect
Subscribers might unsubscribe between the null check and invocation, causing a NullReferenceException.
Which keyword is used to declare an event in C#?
✗ Incorrect
The 'event' keyword declares an event in C#.
Explain how to raise events safely in C# and why it is important.
Think about what happens if no one is listening to the event.
You got /4 concepts.
Describe how the null-conditional operator helps with raising events safely.
Look for the operator that looks like a question mark and dot.
You got /3 concepts.