Search code examples
c#winformsdispose

Disposing Font Object in C#


I have the following code

Font font = ComboBox.Font;
if(condition1)
font = new Font(font, FontStyle.Bold);
if(condition2)
  e.Graphics.DrawString("One", font, color, rectangle);
else
  e.Graphics.DrawString("Two", font, color, rectangle);
font.Dispose();

When I run the code analysis, it shows an error that 'font' is not disposed along all exception paths. What's the proper way to dispose it in the above code?

Thanks.


Solution

  • You should not Dispose ComboBox.Font: it should do ComboBox itself. You can create a Font copy instead:

    using (Font font = new Font(ComboBox.Font, condition1 ? FontStyle.Bold : ComboBox.Font.Style)) {
      if (condition2)
        e.Graphics.DrawString("One", font, color, rectangle);
      else
        e.Graphics.DrawString("Two", font, color, rectangle);
    }