0
0
C Sharp (C#)programming~10 mins

Raising events safely in C Sharp (C#) - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Raising events safely
Define event handler variable
Check if event handler is not null
Skip raising event
Invoke event handler
Event subscribers run their methods
End
This flow shows how to safely raise an event by first checking if there are subscribers before calling the event.
Execution Sample
C Sharp (C#)
public event EventHandler? MyEvent;

public void RaiseEvent()
{
    var handler = MyEvent;
    if (handler != null)
        handler(this, EventArgs.Empty);
}
This code safely raises an event by copying the event delegate to a local variable and checking for null before invoking.
Execution Table
StepActionEvaluationResult
1Copy MyEvent to handlerMyEvent is null or has subscribershandler = MyEvent (snapshot)
2Check if handler != nullIf handler has subscribersTrue or False
3If True, invoke handler(this, EventArgs.Empty)Calls all subscribed methodsSubscribers run their event methods
4If False, skip invocationNo subscribersNo methods called
5End of RaiseEvent methodEvent raised safely or skippedMethod returns
💡 Execution stops after event is invoked or skipped because no subscribers exist.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3/4Final
MyEventnull or delegate listSame as startSame as startSame as startSame as start
handlerundefinedCopy of MyEventSame as after step 1Invoked or not invokedSame as after step 1
Key Moments - 2 Insights
Why do we copy the event delegate to a local variable before checking for null?
Copying to a local variable prevents the event from becoming null between the null check and invocation, avoiding a possible NullReferenceException as shown in step 1 and 2 of the execution_table.
What happens if we invoke the event without checking for null?
If no subscribers exist (MyEvent is null), invoking it directly causes a NullReferenceException. The execution_table step 2 shows the importance of the null check to avoid this.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'handler' after step 1 if MyEvent has two subscribers?
AA copy of MyEvent delegate with two subscribers
Bnull
CAn empty delegate
DThrows an exception
💡 Hint
Refer to execution_table row 1 where handler is assigned a snapshot of MyEvent.
At which step does the program decide not to invoke the event because there are no subscribers?
AStep 1
BStep 3
CStep 4
DStep 2
💡 Hint
Check execution_table row 4 where invocation is skipped if handler is null.
If we remove the local copy and invoke MyEvent directly, what risk do we introduce?
ANo risk, code runs faster
BPossible NullReferenceException if subscribers unsubscribe between check and invoke
CEvent will never be raised
DSubscribers will be called twice
💡 Hint
See key_moments explanation about copying to local variable to avoid null changes.
Concept Snapshot
Raising events safely in C#:
- Copy event delegate to local variable
- Check if local variable is not null
- Invoke local variable to raise event
- Prevents NullReferenceException if subscribers change
- Always use this pattern when raising events
Full Transcript
This example shows how to raise events safely in C#. First, the event delegate is copied to a local variable to prevent it from changing between the null check and invocation. Then, the code checks if the local variable is not null, meaning there are subscribers. If so, it invokes the event, calling all subscribed methods. If no subscribers exist, it skips invocation to avoid errors. This pattern prevents runtime exceptions and ensures safe event raising.