views:

829

answers:

5

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?

+4  A: 

With the code you have there it will close the file once it exits the using block, so you do not need to call close explcitly.

The only reason not to use the using statement would be if you want the file to still be open after you are done with your BinaryWriter, in which case you should hold on to a reference of it instead of passing it into the constructor like that.

John JJ Curtis
+12  A: 

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

LukeH
+2  A: 

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();
    }
}
RichardOD
A: 

The using block will automaticlly close the binary writer and put it in a state to be GC'ed. Using blocks are syntactic sugar for doing the exception handling and closing of the stream yourself.

Tony
A: 

By wrapping the writer up in a using block, the close will automatically happen when the writer is disposed. So in this case, you don't need to explicitly close the writer.

tvanfosson