Having the following:
StringWriter sw = null;
try
{
sw = new StringWriter();
using (var xw = new XmlTextWriter(sw))
{
doc.WriteTo(xw);
return sw.ToString();
}
}
finally
{
sw?.Dispose();
}
triggers the CA2202 (do not dispose objects multiple times) warning in Visual Studio 2015.
But the warning is not triggered if change the fianlly
block to:
finally
{
if (sw != null)
{
sw.Dispose();
}
}
Is that some strangeness of the null-conditional operator in a finally
block or something, or do the analysis tools in Visual Studio simply not understand it?
EDIT: Possibly related: Why does Code Analysis flag me when using the null conditional operator with Dispose()?