Which one do I call?
Is it necessary to call both?
Will the other throw an exception if I have already called one of them?
None of the above. You needn't call either Close
or Dispose
.
MemoryStream
doesn't hold any unmanaged resources, so the only resource to be reclaimed is memory. The memory will be reclaimed during garbage collection with the rest of the MemoryStream
object when your code no longer references the MemoryStream
.
If you have a long-lived reference to the MemoryStream
, you can set that reference to null to allow the MemoryStream
to be garbage collected. Close
and Dispose
free neither the steam buffer nor the MemoryStream
object proper.
Since neither Stream
nor MemoryStream
have a finalizer, there is no need to call Close
or Dispose
to cause GC.SuppressFinalize
to be called to optimize garbage collection. There is no finalizer to suppress.
The docs for MemoryStream put it this way:
This type implements the
IDisposable
interface, but does not actually have any resources to dispose. This means that disposing it by directly callingDispose()
or by using a language construct such asusing
(in C#) orUsing
(in Visual Basic) is not necessary.