I found some code that was not correctly wrapping XMLTextWriter and StringWriter with the using clauses. As I'm correcting it, I stumbled on a interesting question:
do I have to explicitly add calls to Close() on each writer or does XMLTextWriter handle calling Close() on StringWriter instance automatically?
using (StringWriter stringWriter = new StringWriter(sb))
{
using (XmlTextWriter writer = new XmlTextWriter(stringWriter))
{
writer.Flush();
writer.Close();
}
// is stringWriter.Close(); required here?
}
Thnx Matt
Usually it is not required if the class in your
usingstatement implementsIDisposablecorrectly (in this case ifStringWriterandXmlTextWritercall theirClosemethods in theDisposemethod implementation).At the end of a
usingblock theDisposemethod will automatically be called.From the Reference Source of the XmlTextWriter.cs class you can see the following line in the
Close()methodwhere the
textWriterwas received in constructor, so the answer to your question is that you don't need to call theClose()method on yourStringWriterinstance, but doing so will do no harm.For more info about
IDisposablecheck out this link.