Search code examples
c#fontscontrolsdispose

Assigning the same font to multiple controls C#


What is the best practice for disposing of Font objects in C# used in several different controls?

As an example, I have several text boxes, labels, and buttons to which I want to assign the same font. I thought of using the following code:

using (Font f = new Font("Calibri", 10.0f))
{
    textbox1.Font = f;
    textbox2.Font = f;
    label1.Font = f;
    button1.Font = f;
}

The problem is that after using f once I can't use it again and I have to declare a new Font object. What is the best practice for these situations? Should I use the following code?

Font f;
f = new Font(...);
textbox1.Font = f;
f.Dispose();

f = new Font(...);
textbox1.Font = f;
...

Thanks for the help.


Solution

  • Why you're disposing your font just after its creation? You still need it (Dispose() should be called when you won't use it any more). You can use code from both examples, they're OK when removing Dispose() and using:

    Font f = new Font("Calibri", 10.0f);
    textbox1.Font = f;
    textbox2.Font = f;
    label1.Font = f;
    button1.Font = f;
    

    Or (it's slightly less efficient because you allocate more unneeded resources unless Font constructor manages a kind of cache, I'm not sure about it):

    textbox1.Font = new Font("Calibri", 10.0f);
    textbox2.Font = new Font("Calibri", 10.0f);
    label1.Font = new Font("Calibri", 10.0f);
    button1.Font = new Font("Calibri", 10.0f);
    

    EDIT
    Little note about resource disposing: of course you should always dispose a resource each time it's possible (simple rule is to always call Dispose() for classes that implements IDisposable). That said you have to do it after you used it, not before. Let's see this code:

    var font = font;
    textbox1.Font = font;
    font.Dispose();
    

    Of course it won't work because textbox1 has a reference to a disposed object (I don't know what will happen, an ObjectDisposedException? Just ignored?). Dispose() should be called only when you won't use that resource again in future and it's not the case because it'll be used by textbox1 to draw its text. A proper use, for example is:

    using (var font = new Font("Calibri", 10.0f))
    {
        e.Graphics.DrawText(Text, font, Brushes.Black, ClientRectangle);
    }
    

    In this case font is used only by code inside using statement and it can be properly and safely disposed (even if in this case you'd better to avoid to create it each time and you should reuse it).