Friday, 28 December 2012

Safe release of resources

If class allocates unmanaged resources (database connections, sockets, window handles, bitmaps...) it has to implement IDisposable interface with a single method Dispose() which deallocates such resources. When user of this class does not need its instance any more, it has to make sure Dispose() is called - even in the case of an exception. This can be achieved by using try-catch-finally block or with using statement:

Some classes in .NET which implement IDisposable have method Close() along with method Dispose(). Dispose() usually calls Close():

...so it's perfectly safe omitting explicit call to Close() when using using statement.

Resources:
Proper use of the IDisposable interface (SO)
close or dispose (SO)
Does Stream.Dispose always call Stream.Close (and Stream.Flush) (SO)
Post a Comment