Reputation: 1089
I know there is something like an 'EventHandlerManager' in .NET. I've read about memory leaks if you don't unsubscribe events before releasing the objects...
I have the following code:
public Person CurrentPerson
{
get { return currentPerson; }
set
{
if (currentPerson!= null) currentPerson.PropertyChanged -= propertyChanged;
currentPerson= value;
currentPerson.PropertyChanged += propertyChanged;
RaisePropertyChanged(() => CurrentPerson);
}
}
This property is something like a temporary placeholder and whenever I call:
CurrentPerson = new Person();
I want listen to its propertyChange event... I am not sure if I prevent the memory leak in case of event handling.
Thanks for help
Upvotes: 0
Views: 441
Reputation: 1579
This will not cause any memory leaks. As you are unsubscribing from the event before removing reference to an object, and then hooking up to the new one when it comes in, this is correct and wont cause a memory leak. As Ivan mentioned you will need to ensure that events are unsubscribed from when disposing the object, there are a couple of ways you can control destruction of the object. either make a destructor by creating a ~(classname) Method or implementing IDisposable if you have other external things to clean up as well. Call Dispose when you are done with the object and you should be confident that cleanup and disposal of the object has been done and you can then de-reference the object.
A side note, if this is structured how your code is actually laid out you will get an exception if something assigns null to your CurrentPerson property if Person is nullable.
Upvotes: 1