Question

All,

I notice one thing while designing a winform. I applied font property on one of the labels and saw that in form.designer.cs InitializeComponent() .net generated code which attached:

this.Lable1.Font=new Font("Arial", 20, .........)

Now this new Font object does not dispose after the control has gone out of InitializeComponent. If I have 20 different objects on my form I will have at least 20 different undisposed Font objects.

As a remediation I have tried putting following lines in InitializeComponent()

Font font1=new Font("Arial",20,"".......)
Lable1.Font=font1;
font1.dispose();

Am I missing something? or is this how .net deals with fonts and potentially leaves Font objects.

Was it helpful?

Solution

If you immediately dispose a resource, you won't be able to use it for the rest of the lifetime of the form.

The Font is being instantiated when the Form is instantiated. When you close the Form, the Font instance (and anything else created in the InitializeComponent() method) will go out of scope and be disposed of too.

Leave everything in the Designer.cs file as-is. There's even the following comment above the InitializeComponent() method:

Do not modify the contents of this method with the code editor.

Any custom edits you make to it are likely to be overwritten anyway, when you start making other changes to the form at design-time. It's normally not a file you need or want to touch.

OTHER TIPS

The framework automatically disposes them on dispose of the parent object (so Control or Form).

When the parent control is closed, it automatically calls the Dispose method and it will boil down.

Also, disposing the font in the InitializeComponents is a bad idea. Create a variable at class level and dispose in the Dispose method. But as explained above, I don't think you need this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top