-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?

Paulo Barretto
  • 155
  • 1
  • 10
  • 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,934
  • 11
  • 59
  • 95
Joshua
  • 40,822
  • 8
  • 72
  • 132