Andreas Brinck Andreas Brinck - 22 days ago 6
C# Question

What happens if I don't call Dispose on the pen object?

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
}

Answer

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:

  1. You should call Dispose explicitly so that you release your unmanaged resources, and
  2. You shouldn't need to worry about the implementation detail of if there is a finalizer and it cleans up the unmanaged resources.

Pen 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.