As MemoryStream is an unmanaged resource does it always have to be disposed?
Given:
1) A method is invoked.
2) A MemoryStream object is created (MemoryStream ms = new MemoryStream();).
3) An exception occurs and is caught from the invoking classes.
The reference on the MemoryStream object is therefore lost. Does this scenario need a try/finally-block (or using-statement)?
You can re-use the MemoryStream by Setting the Position to 0 and the Length to 0. By setting the length to 0 you do not clear the existing buffer, it only resets the internal counters.
MemoryStream encapsulates data stored as an unsigned byte array. The encapsulated data is directly accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application. The current position of a stream is the position at which the next read or write operation takes place.
You would use the FileStream to read/write a file but a MemoryStream to read/write in-memory data, such as a byte array decoded from a string. You would not use a Stream in and of itself, but rather use it for polymorphism, i.e. passing it to methods that can accept any implementation of Stream as an argument.
StreamWriter. Dispose() does close the underlying stream.
In general, all disposable objects must always be disposed.
However, MemoryStream
doesn't actually need to be disposed, since it doesn't have any unmanaged resources. (It's just a byte[]
and an int
)
The only reason it's disposable in the first place is that it inherits the abstract Stream
class, which implements IDisposable
.
Note that every other stream must be disposed.
Any type that implements IDisposable
should have Dispose
called on it either explicitly via a try/catch/finally block or via the using statement.
There are cases such as this where technically the MemoryStream
does not need disposed, however to honor the interface and protect yourself from changes downstream Dispose
should still be called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With