Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a nested using block dispose objects multiple times? [duplicate]

Tags:

c#

.net

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?

like image 921
JonathanPeel Avatar asked Dec 05 '22 06:12

JonathanPeel


1 Answers

The using block itself won't dispose of anything more than once.

The "problem" (and it does really need the quotes because it's only a problem in the most abstract mathematical sense) is that in this specific scenario the StreamWriter takes ownership of the underlying stream, so when the writer is disposed by the inner using it automatically disposes of the stream as well. Then the outer using goes on to dispose of the stream again.

This is not a problem in practice because Stream can be safely disposed of multiple times. If you have to have total correctness you can still make the stream be disposed of only once by using the appropriate StreamWriter constructor that causes the writer to not take ownership of the stream.

like image 127
Jon Avatar answered Jan 04 '23 05:01

Jon