Inside Man
Inside Man

Reputation: 4372

Assign font with using

What is the difference between these two lines of code with Fonts?

lblName.Font = new Font("Arial", 12f);

and

using(Font font = new Font("Arial", 12f))
    lblName.Font = font;

which one is better keeping memory more empty? which one is faster ? etc

Upvotes: 0

Views: 71

Answers (1)

nvoigt
nvoigt

Reputation: 77285

lblName.Font = new Font("Arial", 12f);

This will create a new font and makes the label use that font. If you have multiple labels, you may want to create only one font and set all the labels to the one font, but other than that, this is as good as it gets.

using(Font font = new Font("Arial", 12f))
    lblName.Font = font;

This is creating a font and making the label use it. And then, as the usingblock ends, .Dispose() will be called on the font, making it release all it's unmanaged resources (like I guess an HFONT windows handle). So you label hasn't been painted on screen yet, but it has an invalid font object to do so and will probably show nothing or throw exceptions or revert back to a known good standard.

So long story short: the second one is wrong. Don't use resources after you have disposed them.

Upvotes: 2

Related Questions