A Font
object in Winforms .NET actually encapsulates two things: a description of a typeface, and a handle to a GDI object which represents that typeface. One of those things represents a limited resource (the GDI handle) and the other does not.
While it might have been possible to have controls use the GDI handles of fonts which are used to set their properties, built-in controls do not do so. Instead, the line myControl.Font = myFont;
will cause myControl
to capture a description of the typeface encapsulated by myFont
and make its own Font
object for internal use. The control will ensure that its internal-use Font
object gets disposed when either the control is disposed or its myControl.Font
is set to a different font, but the control will neither dispose myFont
nor care about when or whether it is disposed. Interestingly, it won't care if myFont
had been disposed even before the statement above executed. Assuming nothing else has written it, reading myControl.Font
will return a reference to myFont
rather than the control's internal font object; if myFont
has been disposed, then myControl.Font
will return a reference to a font object which has been disposed (but could still be used to set other controls' Font
properties).
If one wishes to most accurately ensure the prompt cleanup of GDI font resources, any font objects which will be used only as "templates" and won't be used for actual drawing may be disposed as soon as they are created. I don't know whether that should be recommended as a pattern, since I can't find any official documentation of controls' Font
behavior, but it seems wasteful to have font objects holding GDI resources that are never going to be used. It's too bad controls' Font
property doesn't use some sort of documented FontDescription
class which would encapsulate just the typeface description but not the GDI handle, since such a design would make things a lot clearer.