Search code examples
c#serializationxmltextwriterstringwriter

Calling close on passed in member StringWriter to XMLTextWriter


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


Solution

  • Usually it is not required if the class in your using statement implements IDisposable correctly (in this case if StringWriter and XmlTextWriter call their Close methods in the Dispose method implementation).

    At the end of a using block the Dispose method will automatically be called.

    From the Reference Source of the XmlTextWriter.cs class you can see the following line in the Close() method

    textWriter.Close();
    

    where the textWriter was received in constructor, so the answer to your question is that you don't need to call the Close() method on your StringWriter instance, but doing so will do no harm.

    For more info about IDisposable check out this link.