Let’s say I’ve got a MyObject object that has two interfaces: IMyContract and IDisposable. And I have this code in a method:
IMyContract blah = new MyObject();
blah.Blah();
return;
This is a potential memory leak, right? Doesn’t it need to be:
using (MyObject blah = new MyObject())
{
blah.Blah();
}
return;
Well, if it implements
IDisposableyou should indeed dispose it. There’s no saying what will leak if you don’t – or for how long – but you should have ausingstatement to avoid it anyway.(Just to clarify: memory is the least likely thing to be leaked, as
IDisposableis generally about unmanaged resources such as network connections etc. It’s possible, of course – the object could have a handle on some memory allocated far away from the GC’s gaze. Any implementation ofIDisposablewhich holds direct references to unmanaged resources should also have a finalizer, so the leak should only be temporary… but that could still be painful.)