views:

73

answers:

1

Possible Duplicate:
Why does C# require you to write a null check every time you fire an event?

I see often the following code but somehow don't get it.

if (PropertyChanged != null)
    PropertyChanged(this, new PropertyChangedEventArgs("UIState"));

Why do i need to check if the event is null before rasing it. All of the time, at least when I try it, I can get away with just raising the event.

+4  A: 

It has nothing to do with INotifyPropertyChanged. Any event that has no event handlers registered can be null, and if you try to call PropertyChanged (or any event) when it is null you will get a NullReferenceException.

There is no guarantee that PropertyChanged will never be null. It just so happens that you've always called it when an event handler was registered.

shf301