Reputation: 21088
Is it a good practice in c#, to set all event handler to null in a class destrcutor to be sure, that no memory leaks can occure?
For example:
~SomeClass()
{
OnLoaded = null;
OnUnloaded = null;
}
Or is this really bad practice?
Thank you!
Upvotes: 0
Views: 138
Reputation: 14896
Short answer: it is a bad practice.
You should only use finalizers to clean up unmanaged resources. The garbage collector can take care of all managed objects.
Implementing unnecessary finalizers hurts performance, as the garbage collector has more work to do. Objects with finalizers will take 2 garbage collections to be released from memory.
The Finalize method is executed by the garbage collector before it releases the object from memory. It will only do it if the object is no longer reachable from your program - so other objects also cannot be reached through references held by this object. Setting the references to null will not change anything.
You can find more information about garbage collection on MSDN (https://msdn.microsoft.com/en-us/library/vstudio/ee787088(v=vs.110).aspx) or Eric Lippert's blog (e.g. http://ericlippert.com/2015/05/18/when-everything-you-know-is-wrong-part-one/)
Upvotes: 1