0

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

Inside Man
  • 4,194
  • 12
  • 59
  • 119
  • What should the label use once the font is disposed? Usually, disposing an instance leave it unusable... – Zohar Peled Nov 13 '17 at 08:20
  • 5
    did you try the second code snippet out? – Mong Zhu Nov 13 '17 at 08:28
  • `System.Drawing.Font` has `IDisposable` interface implementation - you can use `using` block for it, but `using` block should reserved for objects which require immediate disposal after usage such like database connections. – Tetsuya Yamamoto Nov 13 '17 at 08:39
  • 1
    Possible duplicate of [Uses of "using" in C#](https://stackoverflow.com/questions/75401/uses-of-using-in-c-sharp) – Owen Pauling Nov 13 '17 at 09:21

1 Answers1

2
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.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • But I'm using the `using` and the font and labels will work without any problems. My goal is to have the least memory usage. – Inside Man Nov 13 '17 at 09:01
  • @Nofuzy Such optimizations shouldn't be your priority, though that is another discussion. The answer is correct, you should not be using disposed objects. Your code shouldn't be working without problems; i don't get why it does, but somewhere in the future it may (will) break. – MarkO Nov 13 '17 at 09:10
  • @Nofuzy The `using` in *this* case is not an *optimization*, it's **wrong**. Period. Accessing a disposed object is plain wrong. Reducing the memory footprint of a .NET Winforms app by fiddling with single fonts is... interesting... to put it mildly. Like picking your bumper sticker for it's wind resistance value. Sure it's optimized, but it's really not the right spot to optimize your car for performance. – nvoigt Nov 13 '17 at 10:10