0

What is the difference between these two lines of code?

btnSubmit.Image = new Bitmap(MyApp.Properties.Resources.TargetImage);
btnSubmit.Image = MyApp.Properties.Resources.TargetImage;

Which one is better for managing memory and keeping it more empty from load and keeping images?

Inside Man
  • 4,194
  • 12
  • 59
  • 119
  • One creates a new (redundant) object in memory, the other uses an object that already exists. So naturally the second line will be much better. If I recall correctly whenever you create a new `Bitmap` object you _must always_ dispose of the object when you're done with it, so that's a double whammy right there. – Prime Nov 01 '17 at 14:45
  • The first one has a bug, the bitmap object returned by the TargetImage property is never going to be disposed. That is not necessarily fatal, but we hear from SO users that have their program crash because of undisposed bitmaps all the time. That a property returns a disposable object every single time you use it was pretty bad Microsoft design and trips up programmers frequently. .NET 1.0 were training wheels. – Hans Passant Nov 01 '17 at 14:51
  • @hanspassant: You mean the second one I think – CodingYoshi Nov 01 '17 at 15:07
  • @HansPassant I have the same problem with undisposed bitmaps, https://stackoverflow.com/q/47050744/709507 , this is because I'm asking this question. – Inside Man Nov 01 '17 at 15:10
  • 1
    @Coding - No, I meant the first. The second one gives the programmer a fighting chance to dispose btnSubmit.Image. No such chance in the first one, that would only dispose the created Bitmap() and not the bitmap returned by the property. – Hans Passant Nov 01 '17 at 15:13
  • @hanspassant got it. Good to know. – CodingYoshi Nov 01 '17 at 15:15

0 Answers0