tags:

views:

132

answers:

4

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?

+6  A: 

It is good practice to close your streams. Use the using statement, and Dispose() will be called when it falls out of scope (or if an exception is thrown), which will in turn close your stream.

static string SerialiseObjectToBase64(object obj)
{
    using (var mstream = new MemoryStream())
    {
        ...
        return Convert.ToBase64String(mstream.ToArray());
    } 
}
Greg
@Greg - It will certainly be closed automatically when the finalizer is run. However there is no guarantee WHEN it will be closed (might just be when the process exits) - so as you point out using 'using' is always a good idea.
Aaron
@Aaron - Thanks, I updated my answer.
Greg
+10  A: 

With a MemoryStream it is a bit of a moot point - since you are ultimately talking to a managed byte[] (so it is still going to wait for routine garbage collection). But in general, yes: you should close (better: Dispose() via using, 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" on Flush() - they need to be Close()d (compression streams in particular).

Marc Gravell
+3  A: 

.Net's GC is very... lazy. Just because a reference has been lost doesn't mean it's immediately swept up, crushed and sent to the landfill. It's always a good idea to close open resources and to dispose of objects that implement IDisposable for that very reason.

Payton Byrd
+3  A: 

Closing streams and disposing of objects are 2 different things. Closing streams flushes the write buffer and writes any unwritten data to the stream. Disposing of the stream will simply release the memory used by the stream variable.

icemanind
This is incorrect. Disposing of a stream *will* close and flush it... but it *won't* release any memory.
Jon Skeet