.NET Close or Dispose?

27 Apr 2010. comments

Usually in .NET resource objects that have a handle on I/O provide the following methods:

obj.Open();
obj.Close();
obj.Dispose();

C# provides some nice syntactic sugar to manage the lifecycle of open/dispose with using, but what about Close() ?

using(var foo = new Connection())
{
    foo.Bar();
    foo.Close(); // necessary?
}
// 'using' block calls Dispose() implicitly regardless of exceptions

In nearly every case calling Close() and Dispose() will produce identical behavior. Typically calling Close() will close a connection and stop there, while Dispose() will both close the connection and reset the state of the connection (as well as releasing all resources). For this reason you can safely call both because calling Close() twice is idempotent. You cannot however call Dispose() twice because it will throw an exception.

So the moral of the story is to call Close() when you intend to reopen the I/O and call Dispose() when you are finished.

comments

Tagged: .NET memory management C#

2017 Ben Lakey

The words here do not reflect those of my employer.