If IDisposable
is implemented properly (with a finalizer that calls Dispose()
and no SuppressFinalize
), the Garbage Collector will get to it eventually. However, using()
is the same as try { ... } finally { object.Dispose(); }
, which will deterministically (explicitly, as soon as possible) dispose. If you depend on the Garbage Collector you may be surprised how long it takes to dispose. If there are unmanaged resources, you could quickly run out of them because they haven't been deallocated.
Edit: I missed the point of this the first time around. Yes, when you use MyObject
you should Dispose()
properly with using()
. If you have other code that uses that interface then you could have something like:
public IMyContract GetInterface()
{
using (MyObject obj = new MyObject())
{
obj.DoSomething();
return (IMyContract)obj;
}
}
The rest of the code can then use IMyContract contract = GetInterface();
without having to worry about (or even knowing) that things should dispose.