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?