What are all the possible ways in which we can get memory leaks in .NET?
I know of two:
- Not properly un-registering Event Handlers/Delegates.
- Not disposing dynamic child controls in Windows Forms:
Example:
// Causes Leaks
Label label = new Label();
this.Controls.Add(label);
this.Controls.Remove(label);
// Correct Code
Label label = new Label();
this.Controls.Add(label);
this.Controls.Remove(label);
label.Dispose();
Update: The idea is to list common pitfalls which are not too obvious (such as the above). Usually the notion is that memory leaks are not a big problem because of the garbage collector. Not like it used to be in C++.
Great discussion guys, but let me clarify... by definition, if there is no reference left to an object in .NET, it will be Garbage Collected at some time. So that is not a way to induce memory leaks.
In the managed environment, I would consider it a memory leak if you had an unintended reference to any object that you aren't aware of (hence the two examples in my question).
So, what are the various possible ways in which such a memory leak can happen?
A lot of the things that can cause memory leaks in unmanaged languages can still cause memory leaks in managed languages. For example, bad caching policies can result in memory leaks.
But as Greg and Danny have said, there is no comprehensive list. Anything that can result in holding memory after its useful lifetime can cause a leak.
Exceptions in Finalise (or Dispose calls from a Finaliser) methods that prevent unmanaged resources from being correctly disposed. A common one is due to the programmer assuming what order objects will be disposed and trying to release peer objects that have already been disposed resulting in an exception and the rest of the Finalise/Dispose from Finalise method not being called.