Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The C# idiom is that if an object implements <code>IDisposable</code> then you use a <code>using</code> block. This will allow all resources being used by the object be disposed of properly. You're not suppose to know the implementation details of <code>MemoryStream</code>. What you do know is that it implements <code>IDisposable</code> so you should dispose of it properly. Further, you think that you know now that it doesn't need to free any resources but how do you know that in the future <code>MemoryStream</code> won't change its underlying implementation so that it does use resources that need to be freed using <code>Dispose</code>? You don't, so since it implements <code>IDispoable</code> you have more future-proof code by just using the pattern now. Second, what if you change your code in the future to use a different type of <code>Stream</code> that does have managed resources? By wrapping the <code>MemoryStream</code> in a <code>using</code> block now you reduce maintenance issues in the future; again, this is the correct way to use objects, and specifically <code>Stream</code>s that implement <code>IDisposable</code>. Third, it's a clear way to signal to readers that you are done using the object; it's what readers of your code will expect to see when they see you are using objects that implement <code>IDisposable</code>. Finally, this is the current implementation of <code>MemoryStream.Dispose</code>:</p> <pre><code>protected override void Dispose(bool disposing) { try { if (disposing) { this._isOpen = false; this._writable = false; this._expandable = false; } } finally { base.Dispose(disposing); } } </code></pre> <p>So, this marks the stream as closed, not-writable and not-growable. If somehow someone else got a hold of a reference to the same <code>MemoryStream</code>, it now becomes unusable to them which could be a good thing. But this is really the least important issue; the implementation details don't matter.</p> <p>Use a <code>using</code> block because <code>MemoryStream</code> implement <code>IDispoable</code>. Don't not use a <code>using</code> block because you think that <code>MemoryStream</code> doesn't have any resources that need to be freed.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload