-3

Suppose I have the code:

void Method1() {
    Bitmap bitmap1;
    foreach (string name in OpenFileDialog1.FileNames) {
        bitmap1 = new Bitmap(name);
        ... // process bitmap
        bitmap1.Dispose();
    }
}

Is Dispose() necessary inside the loop?

  • 3
    Possible duplicate of [.Net and Bitmap not automatically disposed by GC when there is no memory left](http://stackoverflow.com/a/5838632/448144) The marked answer should explain why you need to dispose of it. – Nope Feb 23 '17 at 14:32

1 Answers1

0

Oh yeah. That bitmap object is holding a memory map open on the file!

Better method as this code structure can use using:

void Method1() {
    foreach (string name in OpenFileDialog1.FileNames) {
        using (var bitmap1 = new Bitmap(name))
        {
            ... // process bitmap
        }
    }
}
Ðаn
  • 10,679
  • 11
  • 60
  • 94
Joshua
  • 38,744
  • 8
  • 68
  • 123