What's the best practice for nested using statement?

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Text below is the demo code.
public void Save()<br/>
{
byte[] buffer;<br/>
using (var memoryStream = new MemoryStream())<br/>
{<br/>
using (var writer = new BinaryWriter(memoryStream))<br/>
{<br/>
writer.Write(_childs.Count);
foreach (var childInfo in _childs)<br/>
{<br/>
childInfo.Write(writer);<br/>
}<br/>
}
buffer = memoryStream.ToArray();<br/>
}
// Some other code.
}
Both MemoryStream and BinaryWriter are disposable type, and instance binaryWriter is creted with memoryStream as its constructor parameter. So i guess in type BinaryWriter there is a MemoryStream type private field, this field is assigned
in constructor with constructor parameter.
According to Dispose pattern, when instance binaryWriter is out of using scope, its Dispose() method will be invoked, in turn its Dispose() method will call Dispose() method of all its disposable fields, which means in the demo code, MemoryStream
will be disposed more than once, i think that is why we will get the CA2202 compile warning(FxCop).
here are my questions:
1. Any best practice that we can use to eleminate this warning?
2. I did some test on demo code, it seems the code works fine except the warning. Then im confused, since memoryStream will be disposed when it goes out of the scope of inner using statement, then it shoud be failed when we try to invoke its ToArray()
method to get the data. Why this still works?

Thanks in advance.



View the full article
 
Back
Top