Search code examples
.netdisposeidisposable

Will the Garbage Collector call IDisposable.Dispose for me?


The .NET IDisposable Pattern implies that if you write a finalizer, and implement IDisposable, that your finalizer needs to explicitly call Dispose. This is logical, and is what I've always done in the rare situations where a finalizer is warranted.

However, what happens if I just do this:

class Foo : IDisposable
{
     public void Dispose(){ CloseSomeHandle(); }
}

and don't implement a finalizer, or anything. Will the framework call the Dispose method for me?

Yes I realise this sounds dumb, and all logic implies that it won't, but I've always had 2 things at the back of my head which have made me unsure.

  1. Someone a few years ago once told me that it would in fact do this, and that person had a very solid track record of "knowing their stuff."

  2. The compiler/framework does other 'magic' things depending on what interfaces you implement (eg: foreach, extension methods, serialization based on attributes, etc), so it makes sense that this might be 'magic' too.

While I've read a lot of stuff about it, and there's been lots of things implied, I've never been able to find a definitive Yes or No answer to this question.


Solution

  • The .Net Garbage Collector calls the Object.Finalize method of an object on garbage collection. By default this does nothing and must be overidden if you want to free additional resources.

    Dispose is NOT automatically called and must be explicity called if resources are to be released, such as within a 'using' or 'try finally' block

    see http://msdn.microsoft.com/en-us/library/system.object.finalize.aspx for more information