Johannes Schacht Johannes Schacht - 1 year ago 190
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);

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download