Search code examples
.netvb.netfilestreamusing-statement

When to use the Using statement


I think I may be using the Using statement wrong here. What would be a better way of writing this?

Dim x As New Serialization.XmlSerializer( ... )
Using file As New FileStream(myFile, FileMode.Create)
   Using writer As XmlWriter = XmlTextWriter.Create(file)
      x.Serialize(writer, myCollection)
   End Using
End Using

I've read that you're only supposed to use a using block on objects that have a .Dispose() (i.e. implements IDisposable), which is why I'm thinking there shouldn't be a Using on "writer", but instead a writer.Close() at the end. But "file" has both a .Dispose() and a .Close(), so which do I use? The using or file.Close()?

Note: I'm using an XmlWriter because I can customize the output. I removed the settings here, though.


Solution

  • Both FileStream and XmlWriter implement IDisposable - the code is correct. Actually the compiler probably wouldn't let you do this if it was wrong. If there isn't a public .Dispose(), then it must be using explicit interface implementation - but that doesn't change your responsibility for calling .Dispose(). For interest, in C# you can avoid the ever-increasing nesting/indenting, i.e.

    using(...a...)
    using(...b...)
    using(...c...)
    {
       ...
    }
    

    but fundamentally your current code is correct.