As a java developer getting into .NET I\'d like to understand the IDisposable interface. Could somebody please try to explain this and how it differs from what happens in Java?
Basically IDisposable at a high level, combined with the using
keyword is giving you syntactical support for what you see as a common Java idiom like this:
Connection c = null;
try {
c = getConnection();
....
} finally {
if (c != null) {
c.close();
}
}
If Java had a using keyword and an IDisposable interface with a close()
method, it might look like this:
//psudo-Java
using(Connection c = getConnection()) {
.....
}
With the close method being implicitly called at the end of that block. No need for try/finally.
That being said, IDisposible has a fairly complex contract, and is mainly concerned with freeing unmanaged memory. You have to work hard with Java to have unmanaged memory (basically with JNI and Swing components, you have the concept), but it is much more common in .NET, so there is language support for the concept.