Is a memory leak created if a MemoryStream in .NET is not closed?
Yes there's a leak, depending on how you define LEAK and how much LATER you mean...
If by leak you mean "the memory remains allocated, unavailable for use, even though you're done using it" and by latter you mean anytime after calling dispose, then then yes there may be a leak, although its not permanent (i.e. for the life of your applications runtime).
To free the managed memory used by the MemoryStream, you need to unreference it, by nullifying your reference to it, so it becomes eligible for garbage collection right away. If you fail to do this, then you create a temporary leak from the time you're done using it, until your reference goes out of scope, because in the meantime the memory will not be available for allocation.
The benefit of the using statement (over simply calling dispose) is that you can DECLARE your reference in the using statement. When the using statement finishes, not only is dispose called, but your reference goes out of scope, effectively nullifying the reference and making your object eligible for garbage collection immediately without requiring you to remember to write the "reference=null" code.
While failing to unreference something right away is not a classical "permanent" memory leak, it definitely has the same effect. For example, if you keep your reference to the MemoryStream (even after calling dispose), and a little further down in your method you try to allocate more memory... the memory in use by your still-referenced memory stream will not be available to you until you nullify the reference or it goes out of scope, even though you called dispose and are done using it.
You won't leak anything - at least in the current implementation.
Calling Dispose won't clean up the memory used by MemoryStream any faster. It will stop your stream from being viable for Read/Write calls after the call, which may or may not be useful to you.
If you're absolutely sure that you never want to move from a MemoryStream to another kind of stream, it's not going to do you any harm to not call Dispose. However, it's generally good practice partly because if you ever do change to use a different Stream, you don't want to get bitten by a hard-to-find bug because you chose the easy way out early on. (On the other hand, there's the YAGNI argument...)
The other reason to do it anyway is that a new implementation may introduce resources which would be freed on Dispose.
If something is Disposable, you should always Dispose it. You should be using a using
statement in your bar()
method to make sure ms2
gets Disposed.
It will eventually get cleaned up by the garbage collector, but it is always good practice to call Dispose. If you run FxCop on your code, it would flag it as a warning.