I’ve been told that System.IO.MemoryStream need not be wrapped in a using block because there is no underlying resource, this kinda goes against what i’ve always been told about streams (“if in doubt, use a using“).
Is this true? Why then does MSDN example use one (summarized below)?
using(MemoryStream memStream = new MemoryStream(100))
{
// do stuff
}
The C# idiom is that if an object implements
IDisposablethen you use ausingblock. This will allow all resources being used by the object be disposed of properly. You’re not suppose to know the implementation details ofMemoryStream. What you do know is that it implementsIDisposableso 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 futureMemoryStreamwon’t change its underlying implementation so that it does use resources that need to be freed usingDispose? You don’t, so since it implementsIDispoableyou 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 ofStreamthat does have managed resources? By wrapping theMemoryStreamin ausingblock now you reduce maintenance issues in the future; again, this is the correct way to use objects, and specificallyStreams that implementIDisposable. 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 implementIDisposable. Finally, this is the current implementation ofMemoryStream.Dispose: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
MemoryStream, 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.Use a
usingblock becauseMemoryStreamimplementIDispoable. Don’t not use ausingblock because you think thatMemoryStreamdoesn’t have any resources that need to be freed.