Aug 6, 2015

RePost : C# - using statement tips

When using any class that implements IDisposable it is advisable to use using statement.

Now what I didn't know is that using statement is replacement for try finally with call to dispose.

Furthermore call to dispose internally calls Close() for Streams I think.

So using statement is real champion :)

Instead of:

try{

Stream s = new Stream();

}
finally
{
s.Flush();
s.Close();
s.Dispose();
}

Just this:

using ( Stream s = new Stream())
{
}

Important!

Flush() is NOT called automatically !
So using takes care of connections and resources but does not takes care that your data will be flushed from cache.
This makes sense since it primary protects from exceptions and developer should think about Flush().

http://stackoverflow.com/questions/911408/does-stream-dispose-always-call-stream-close-and-stream-flush

No comments:

Post a Comment