1

When I wrap IDisposable objects in usings like this I get the code analysis warning Code analysis error CA2202: Do not dispose objects multiple times, http://msdn.microsoft.com/en-us/library/ms182334.aspx

using (StringWriter textWriter = new StringWriter())
{
    using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
    {
        serializer.Serialize(xmlWriter, value);
    }
    return textWriter.ToString();
}

This however doesn't return any errors

using (StringWriter textWriter = new StringWriter())
{
    XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings);
    serializer.Serialize(xmlWriter, value);
    return textWriter.ToString();
}

Also when doing this the xmlWriter dispose will trigger CA2202

StringWriter textWriter = null;
XmlWriter xmlWriter = null;

try
{
    textWriter = new StringWriter();
    xmlWriter = XmlWriter.Create(textWriter, settings);
    serializer.Serialize(xmlWriter, value);
    return textWriter.ToString();
}
finally
{
    if (textWriter != null)
        textWriter.Dispose();
    // The xmlWriter dispose will trigger CA2202
    if (xmlWriter != null)
        xmlWriter.Dispose();
}

Which pattern shall I use? It seems strange to not dispose disposable elements.

Eric Herlitz
  • 25,354
  • 27
  • 113
  • 157

2 Answers2

2

Ath the end of the inner using statement XmlWriter is being disposed. When this happens the textWriter element is also disposed because XmlWriter internally disposes object it wraps.

Since Dispose should be idempotent (repeatable calls does not have side effects) I wouldn't worry about this warning.

nan
  • 19,595
  • 7
  • 48
  • 80
1

A simple google find this answer: https://stackoverflow.com/a/8096857/2027232

The problem isn't because of the nested usings. They're fine and generally recommended. The problem here is that XmlReader will dispose the TextReader if you pass an XmlReaderSettings with CloseInput == true, but the CA2202 rule isn't smart enough that your code won't go down that branch. Keep your nested usings, and suppress the CA2202 violation as a false positive. If you want to be extra careful, use an XmlReaderSettings with CloseInput set to false, but that is the default value, so it's not strictly necessary.

BTW, there are similar CA2202 problem scenarios for a variety of stream and reader types. Unfortunately, they're not all the same as this one, so the best case handling can differ depending on which type is cause the problem.

Community
  • 1
  • 1
string.Empty
  • 10,393
  • 4
  • 39
  • 67