2

I have the following code which has a 'PropertyChangedEventHandler'. I see it has a property PropertyChangedEventHandler, but I don't see anywhere it calls 'new PropertyChangedEventHandler'? And do I need to 'null' the reference when I don't need it?

public abstract class MyClass: INotifyPropertyChanged
{
    public event PropertyChangedEventHandler eventHandler;     
}
Gericke
  • 2,109
  • 9
  • 42
  • 71
n179911
  • 19,547
  • 46
  • 120
  • 162
  • possible duplicate of [Understanding events and event handlers in C#](http://stackoverflow.com/questions/803242/understanding-events-and-event-handlers-in-c-sharp) – poke Jul 22 '15 at 07:05

2 Answers2

3

When you declare an event, the compiler automatically creates a backing field of the target delegate type and two wrapper methods, called "add" and "remove". When you subscribe to the event, the "add" method is internally called and it creates an instance of the underlying delegate(PropertyChangedEventHandler in this case) if not already created.

When you unsubscribe from the event, "remove" method is internally called. If there are no more subscribers, the underlying delegate field is automatically set to null in the "remove" method. So you don't need to set it to null explicitly.

And this is the reason you need to check for null reference before raising the event, because, if there are no subscribers, the underlying field will be null.

Tom Lint
  • 483
  • 5
  • 13
Deepak Bhatia
  • 1,090
  • 1
  • 8
  • 13
  • I am investigate why PropertyChangedEventHandler objects are not being freed. I suspect there are still some subscriber in the code which are being held (incorrectly) and causing PropertyChangedEventHandler not being freed. Is there a way to check for how many subscriber for a PropertyChangedEventHandler ? – n179911 Jul 24 '15 at 17:12
1

This is declared as an event. By default, an event is automatically created as a multicast delegate that can have delegates added to and removed from.

So no, you don't need to do anything. The framework will initialize it and free it as appropriate.

Andrew Shepherd
  • 44,254
  • 30
  • 139
  • 205