What happens if I don't call Dispose
on the pen
object in this code snippet?
private void panel_Paint(object sender, PaintEventArgs e)
{
var pen = Pen(Color.White, 1);
//Do some drawing
}
The Pen
will be collected by the GC at some indeterminate point in the future, whether or not you call Dispose
.
However, any unmanaged resources held by the pen (e.g., a GDI+ handle) will not be cleaned up by the GC. The GC only cleans up managed resources. Calling Pen.Dispose
allows you to ensure that these unmanaged resources are cleaned up in a timely manner and that you aren't leaking resources.
Now, if the Pen
has a finalizer and that finalizer cleans up the unmanaged resources then those said unmanaged resources will be cleaned up when the Pen
is garbage collected. But the point is that:
Dispose
explicitly so that you release your unmanaged resources, andPen
implements IDisposable
. IDisposable
is for disposing unmanaged resources. This is the pattern in .NET.
For previous comments on the this topic, please see this answer.