When does this Font object get disposed?

.net, c#, garbage-collection

Solution

`Font` has finalizer declared:

~Font()
{
    this.Dispose(false);
}

When font object created, it's registered in finalization queue. Such objects are not destroyed (i.e. memory stays allocated) during garbage collection - they destroyed later, when finalizers called (btw finalizer could be never executed). Thus better call `Dispose` manually or via `using` statement. In this case font object will be disposed and unregistered from finalization (thus it will be removed from memory during garbage collection):

public void Dispose()
{
    this.Dispose(true);
    GC.SuppressFinalize(this);
}

You can read more about garbage collection and finalization in Jeffrey Richter's article

Problem

I have a line in my C# code that creates a font in order to measure the length of a string: ``` int width = (int)(myGraphics.MeasureString(text, new Font(myFontName, myFontSize, FontStyle.Bold)).Width); ``` My question is, when is the `new Font()` variable disposed? Is it disposed when the form is disposed, or is it immediate?

Original source