Is it always necessary to close streams or, because .net is managed code, will it be closed automatically as soon as it drops out of scope (assuming there are no exceptions raised).
Illustrated:
static string SerialiseObjectToBase64(object obj)
{
var mstream = new MemoryStream();
...
return Convert.ToBase64String(mstream.ToArray());
}
Is the above code acceptable?
With a
MemoryStreamit is a bit of a moot point – since you are ultimately talking to a managedbyte[](so it is still going to wait for routine garbage collection). But in general, yes: you should close (better:Dispose()viausing, so it gets shut down upon exception) the stream when done, otherwise you might not flush some data to the underlying (unmanaged) destination. And there are some streams that don’t actually fully “flush” onFlush()– they need to beClose()d (compression streams in particular).