45

When using a memory stream in a using statement do I need to call close? For instance is ms.Close() needed here?

  using (MemoryStream ms = new MemoryStream(byteArray)) 
    {  
      // stuff 

      ms.Close(); 
    }
AJM
  • 32,054
  • 48
  • 155
  • 243

2 Answers2

71

No, it's not.

using ensures that Dispose() will be called, which in turn calls the Close() method.

You can assume that all kinds of Streams are getting closed by the using statement.

From MSDN:

When you use an object that accesses unmanaged resources, such as a StreamWriter, a good practice is to create the instance with a using statement. The using statement automatically closes the stream and calls Dispose on the object when the code that is using it has completed.

sloth
  • 99,095
  • 21
  • 171
  • 219
  • 3
    I realize this is old, but I would just like to add that using a `.Close()` in addition to the `using` will also cause code analysis warning "CA2202: Do not dispose objects multiple times". For more information, read the "Cause" section here: http://msdn.microsoft.com/query/dev12.query?appId=Dev12IDEF1&l=EN-US&k=k(CA2202);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.0) – Adam Plocher Nov 18 '13 at 22:50
  • Is it not the other way around. That `.Close()` will call `.Dispose()`? https://msdn.microsoft.com/en-us/library/system.io.stream.close(v=vs.110).aspx – Levi Aug 08 '17 at 09:31
  • Dispose() calls Close() which calls Dispose(boolean). – sloth Aug 08 '17 at 20:30
8

When using a memory stream in a using statement do I need to call close?

No, you don't need. It will be called by the .Dispose() method which is automatically called:

using (MemoryStream ms = new MemoryStream(byteArray)) 
{  
    // stuff 
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 3
    @HenkHolterman Actually `Dispose()` calls `Close()` which in turn calls `Dispose(true)`. – sloth Aug 15 '12 at 12:02