Johannes Schacht Johannes Schacht - 3 months ago 43
C# Question

CA2202: How to circumvent the warning?

I ran my code through code analysis in visual studio 2015. It shows a warning that I do not know how to circumvent. The below snippet shows the principle. This program produces the warning CA2202:


"Object 'memoryStream' can be disposed more than once in method...".


private void tt()
{
MemoryStream memoryStream = null;
StreamWriter streamWriter = null;
memoryStream = new MemoryStream();
streamWriter = new StreamWriter(memoryStream, Encoding.Unicode);
memoryStream.Close();
streamWriter.Close();
}

Answer

The method description of StreamWriter.Close according to the MSDN is "Closes the current StreamWriter object and the underlying stream.". Therefore, memoryStream.Close() and streamWriter.Close() close the underlying stream. This was diagnosed by the compiler and recommended to avoid. Also make sure that you call streamWriter.Close() since this method flushes the buffers in the streamWriter.

Also the using keyword (scoping including a final call on .Dispose() / .Close()) is highly recommendable for these kind of operations. Please refer to the following MSDN page about a typical usage.

Comments