Having this code:
using (BinaryWriter writer = new BinaryWriter(File.Open(ProjectPath, FileMode.Create)))
{
//save something here
}
Do we need to close the BinaryWriter? If not, why?
So long as it's all wrapped up in a using
block then you don't need to explicitly call Close
.
The using
block will ensure that the object is disposed, and the Close
and Dispose
methods are interchangeable on BinaryWriter
. (The Close
method just calls Dispose
behind the scenes.)
Putting it in a using statement as per your code example will call Dispose, which closes the underlying stream, so no. You can see this through Reflector:
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.OutStream.Close();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With