Question

This situation seem very interesting to me.

In C# you need to check if there is any listener to the event in a class before firing it.

Assuming event structure of C# is a non-standart(Meaning Microsoft did it) implementation of Observer observable pattern for ease of use.

Why didn't they implement this inside that structure? Is there solid reasons or documentation for this choice.

Is it a necessity do null checking, or am I wrong in my assumption for event structures needing null checks under all circumstances.

This is a more of a curiosity question looking for an answer to this implementation choice by microsoft. Which I hope will lead to further understanding of delegate and event keyword inner workings.

Was it helpful?

Solution 2

There's a reply to this question in a blog by Eric Gunnerson.

Basically it seems to say that Microsoft thought about changing it, but it would break existing code.

In other words, it was a mistake in the original design for events, but it's too late to fix it.

OTHER TIPS

Yes, you must do the null check.

Calling a delegate that is null results in a NullReferenceException.

You might be tempted to intialize all delegates with a non-null, empty event handler. However, that would be far worse than testing for null, in terms of CPU usage, memory usage, and lines of code.

You can add a default event listener, thus avoiding the null check

public Action<object, EventArgs> SomeEvent = (o, e) => { };

in that way, you can call SomeEvent without checking for null, since it contains a default (empty implementation) listener. Please note that it might hurt performance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top