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
using
statement implementsIDisposable
correctly (in this case ifStringWriter
andXmlTextWriter
call theirClose
methods in theDispose
method implementation).At the end of a
using
block theDispose
method will automatically be called.From the Reference Source of the XmlTextWriter.cs class you can see the following line in the
Close()
methodwhere the
textWriter
was received in constructor, so the answer to your question is that you don't need to call theClose()
method on yourStringWriter
instance, but doing so will do no harm.For more info about
IDisposable
check out this link.