The documentation for this analysis warning ( http://msdn.microsoft.com/en-us/library/ms182334.aspx ) gives this example, similar to yours, that it controls threads:
Stream stream = null; try { stream = new FileStream("file.txt", FileMode.OpenOrCreate); using (StreamWriter writer = new StreamWriter(stream)) { stream = null; // Use the writer object... } } finally { if(stream != null) stream.Dispose(); }
but it still gives an error. The following is the error:
Stream stream = null; StreamWriter writer = null; try { stream = new FileStream("file.txt", FileMode.OpenOrCreate); writer = new StreamWriter(stream)) // Do some stuff on the stream writer.. } finally { if(writer != null) writer.Dispose(); else if(stream != null) stream.Dispose(); }
The reason is simple; if the author will always manage the flow for you. Only in the script is the script not created successfully if you manage the stream yourself. But I have to admit that I prefer the following syntax, and if you create a MemoryStream instead of a FileStream, the probability of an exception will be small, and I would prefer to suppress CA. Note that you can add using operators, so an extra level of nesting is often required.
using (Stream stream = new FileStream("file.txt", FileMode.OpenOrCreate)) using (StreamWriter writer = new StreamWriter(stream)) {
NP83
source share