Why is it that a nested using block will dispose an object multiple times?
In reference to CA2202:
In the following example, a Stream object that is created in an outer using statement is released at the end of the inner using statement in the Dispose method of the StreamWriter object that contains the stream object. At the end of the outer using statement, the stream object is released a second time. The second release is a violation of CA2202.
using (Stream stream = new FileStream("file.txt", FileMode.OpenOrCreate))
{
using (StreamWriter writer = new StreamWriter(stream))
{
// Use the writer object...
}
}
I know that in most cases I can use
using ()
using ()
{ }
And when I cannot I am happy to revert to try
finally
like it suggests, I would just like to know why it works with way.
Is it just the best way the generated code can be interpreted, "Okay, as using block is closing, let me dispose all objects." or is there a reason for it working this way?