Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we need to close a C# BinaryWriter or BinaryReader in a using block?

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?

like image 477
david.healed Avatar asked Jul 03 '09 13:07

david.healed


2 Answers

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.)

like image 63
LukeH Avatar answered Oct 09 '22 10:10

LukeH


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();
    }
}
like image 25
RichardOD Avatar answered Oct 09 '22 10:10

RichardOD