2

will a construct like this, dispose the filehandle correctly?

void bla() {
    using (var stream = new new System.IO.StreamReader( filename)) {
        return DoSomethingWithTheStream(stream);
    }
}

i.e. will the using trigger the Dispose even though it is returned inside?

clamp
  • 33,000
  • 75
  • 203
  • 299

4 Answers4

5

This is equivalent to:

var stream = new StreamReader(fileName);
try {
    return DoSomethingWithTheStream(stream);
}
finally {
    stream.Dispose();
}

Since finally clauses are guaranteed to execute, it's guaranteed that the stream is disposed before returning from the method.

Asik
  • 21,506
  • 6
  • 72
  • 131
4

Yes. No matter how the block is left, the resource is disposed. This is the value of the using-block.

usr
  • 168,620
  • 35
  • 240
  • 369
2

Yes, it will dispose correctly.

Raidri
  • 17,258
  • 9
  • 62
  • 65
0

Yes, as soon as stream goes out of scope it will be disposed.

Gerrie Schenck
  • 22,148
  • 20
  • 68
  • 95