MemoryStream in Using Statement - Do I need to call close()

后端 未结 2 782
小鲜肉
小鲜肉 2020-12-17 07:52

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(         


        
2条回答
  •  醉梦人生
    2020-12-17 08:25

    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.

提交回复
热议问题