<p>The .NET <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx" rel="noreferrer">IDisposable Pattern</a> <em>implies</em> 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.</p>

<p>However, what happens if I just do this:</p>

<pre><code>class Foo : IDisposable
{
     public void Dispose(){ CloseSomeHandle(); }
}
</code></pre>

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

<p>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.</p>

<ol>
<li><p>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."</p></li>
<li><p>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. </p></li>
</ol>

<p>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 <strong>definitive</strong> Yes or No answer to this question.</p>

[{'answer_id': 45043, 'author': 'Matt Bishop', 'author_id': 4301, 'author_profile': 'https://Stackoverflow.com/users/4301', 'pm_score': 3, 'selected': False, 'text': '<p>I don\'t think so. You have control over when Dispose is called, which means you could in theory write disposal code that makes assumptions about (for instance) the existence of other objects. You have no control over when the finalizer is called, so it would be iffy to have the finalizer automatically call Dispose on your behalf.</p>\n\n<hr>\n\n<p>EDIT: I went away and tested, just to make sure:</p>\n\n<pre><code>class Program\n{\n    static void Main(string[] args)\n    {\n        Fred f = new Fred();\n        f = null;\n        GC.Collect();\n        GC.WaitForPendingFinalizers();\n        Console.WriteLine("Fred\'s gone, and he\'s not coming back...");\n        Console.ReadLine();\n    }\n}\n\nclass Fred : IDisposable\n{\n    ~Fred()\n    {\n        Console.WriteLine("Being finalized");\n    }\n\n    void IDisposable.Dispose()\n    {\n        Console.WriteLine("Being Disposed");\n    }\n}\n</code></pre>\n'}, {'answer_id': 45048, 'author': 'Brian Leahy', 'author_id': 580, 'author_profile': 'https://Stackoverflow.com/users/580', 'pm_score': 3, 'selected': False, 'text': "<p>Not in the case you describe,\nBut the GC will call the <strong>Finalizer</strong> for you, if you have one.</p>\n\n<p>HOWEVER.  The next garbage collection ,instead of being collected, the object will go into the finalization que, everything gets collected, then it's finalizer called.  The next collection after that it will be freed.</p>\n\n<p>Depending on the memory pressure of your app, you may not have a gc for that object generation for a while.  So in the case of say, a file stream or a db connection, you may have to wait a while for the unmanaged resource to be freed in the finalizer call for a while, causing some issues.</p>\n"}, {'answer_id': 45049, 'author': 'Xian', 'author_id': 4642, 'author_profile': 'https://Stackoverflow.com/users/4642', 'pm_score': 8, 'selected': True, 'text': '<p>The .Net Garbage Collector calls the Object.Finalize method of an object on garbage collection.  By <strong>default</strong> this does <strong>nothing</strong> and must be overidden if you want to free additional resources.</p>\n\n<p>Dispose is NOT automatically called and must be <strong>explicity</strong> called if resources are to be released, such as within a \'using\' or \'try finally\' block</p>\n\n<p>see <a href="http://msdn.microsoft.com/en-us/library/system.object.finalize.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.object.finalize.aspx</a> for more information</p>\n'}, {'answer_id': 45050, 'author': 'penyaskito', 'author_id': 3008, 'author_profile': 'https://Stackoverflow.com/users/3008', 'pm_score': 1, 'selected': False, 'text': '<p>No, it\'s not called.</p>\n\n<p>But this makes easy to don\'t forget to dispose your objects. Just use the <code>using</code> keyword.</p>\n\n<p>I did the following test for this:</p>\n\n<pre><code>class Program\n{\n    static void Main(string[] args)\n    {\n        Foo foo = new Foo();\n        foo = null;\n        Console.WriteLine("foo is null");\n        GC.Collect();\n        Console.WriteLine("GC Called");\n        Console.ReadLine();\n    }\n}\n\nclass Foo : IDisposable\n{\n    public void Dispose()\n    {\n\n        Console.WriteLine("Disposed!");\n    }\n</code></pre>\n'}, {'answer_id': 45051, 'author': 'Rob Walker', 'author_id': 3631, 'author_profile': 'https://Stackoverflow.com/users/3631', 'pm_score': 2, 'selected': False, 'text': '<p>The GC will <strong>not</strong> call dispose.  It <em>may</em> call your finalizer, but even this isn\'t guaranteed under all circumstances.</p>\n\n<p>See this <a href="http://blogs.msdn.com/arich/archive/2004/09/23/233683.aspx" rel="nofollow noreferrer">article</a> for a discussion of the best way to handle this.</p>\n'}, {'answer_id': 45058, 'author': 'Joseph Daigle', 'author_id': 507, 'author_profile': 'https://Stackoverflow.com/users/507', 'pm_score': 0, 'selected': False, 'text': '<p>The documentation on <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx" rel="nofollow noreferrer">IDisposable</a> gives a pretty clear and detailed explaination of the behavior, as well as example code. The GC will NOT call the <code>Dispose()</code> method on the interface, but it will call the finalizer for your object.</p>\n'}, {'answer_id': 45087, 'author': 'Cory Foy', 'author_id': 4083, 'author_profile': 'https://Stackoverflow.com/users/4083', 'pm_score': 6, 'selected': False, 'text': "<p>I want to emphasize Brian's point in his comment, because it is important.</p>\n\n<p>Finalizers are not deterministic destructors like in C++. As others have pointed out, there is no guarantee of when it will be called, and indeed if you have enough memory, if it will <em>ever</em> be called.</p>\n\n<p>But the bad thing about finalizers is that, as Brian said, it causes your object to survive a garbage collection. This can be bad. Why?</p>\n\n<p>As you may or may not know, the GC is split into generations - Gen 0, 1 and 2, plus the Large Object Heap. Split is a loose term - you get one block of memory, but there are pointers of where the Gen 0 objects start and end. </p>\n\n<p>The thought process is that you'll likely use lots of objects that will be short lived. So those should be easy and fast for the GC to get to - Gen 0 objects. So when there is memory pressure, the first thing it does is a Gen 0 collection. </p>\n\n<p>Now, if that doesn't resolve enough pressure, then it goes back and does a Gen 1 sweep (redoing Gen 0), and then if still not enough, it does a Gen 2 sweep (redoing Gen 1 and Gen 0). So cleaning up long lived objects can take a while and be rather expensive (since your threads may be suspended during the operation).</p>\n\n<p>This means that if you do something like this:</p>\n\n<pre><code>~MyClass() { }\n</code></pre>\n\n<p>Your object, no matter what, will live to Generation 2. This is because the GC has no way of calling the finalizer during garbage collection. So objects that have to be finalized are moved to a special queue to be cleaned out by a different thread (the finalizer thread - which if you kill makes all kinds of bad things happen). This means your objects hang around longer, and potentially force more garbage collections.</p>\n\n<p>So, all of that is just to drive home the point that you want to use IDisposable to clean up resources whenever possible and seriously try to find ways around using the finalizer. It's in your application's best interests.</p>\n"}, {'answer_id': 45383, 'author': 'Erick Sgarbi', 'author_id': 4171, 'author_profile': 'https://Stackoverflow.com/users/4171', 'pm_score': 0, 'selected': False, 'text': "<p>The IDisposable pattern was created primarily to be called by the developer, if you have an object that implements IDispose the developer should either implement the <code>using</code> keyword around the context of the object or call the Dispose method directly.</p>\n\n<p>The fail safe for the pattern is to implement the finalizer calling the Dispose() method. If you don't do that you may create some memory leaks i.e.: If you create some COM wrapper and never call the System.Runtime.Interop.Marshall.ReleaseComObject(comObject) (which would be placed in the Dispose method).</p>\n\n<p>There is no magic in the clr to call Dispose methods automatically other than tracking objects that contain finalizers and storing them in the Finalizer table by the GC and calling them when some clean up heuristics kick in by the GC.</p>\n"}, {'answer_id': 45541, 'author': 'Andrew', 'author_id': 1948, 'author_profile': 'https://Stackoverflow.com/users/1948', 'pm_score': 5, 'selected': False, 'text': "<p>There's lots of good discussion already here, and I'm a little late to the party, but I wanted to add a few points myself.</p>\n\n<ul>\n<li>The Garbage collecter will never directly execute a Dispose method for you.</li>\n<li>The GC <em>will</em> execute finalizers when it feels like it.</li>\n<li>One common pattern that is used for objects that have a finalizer is to have it call a method which is by convention defined as Dispose(bool disposing) passing false to indicate that the call was made due to finalization rather than an explicit Dispose call.</li>\n<li>This is because it is not safe to make any assumptions about other managed objects while finalizing an object (they may have already been finalized).</li>\n</ul>\n\n<pre><code>\nclass SomeObject : IDisposable {\n IntPtr _SomeNativeHandle;\n FileStream _SomeFileStream;\n\n // Something useful here\n\n ~ SomeObject() {\n  Dispose(false);\n }\n\n public void Dispose() {\n  Dispose(true);\n }\n\n protected virtual void Dispose(bool disposing) {\n  if(disposing) {\n   GC.SuppressFinalize(this);\n   //Because the object was explicitly disposed, there will be no need to \n   //run the finalizer.  Suppressing it reduces pressure on the GC\n\n   //The managed reference to an IDisposable is disposed only if the \n   _SomeFileStream.Dispose();\n  }\n\n  //Regardless, clean up the native handle ourselves.  Because it is simple a member\n  // of the current instance, the GC can't have done anything to it, \n  // and this is the onlyplace to safely clean up\n\n  if(IntPtr.Zero != _SomeNativeHandle) {\n   NativeMethods.CloseHandle(_SomeNativeHandle);\n   _SomeNativeHandle = IntPtr.Zero;\n  }\n }\n}\n</code></pre>\n\n<p>That's the simple version, but there are a lot of nuances that can trip you up on this pattern.  </p>\n\n<ul>\n<li>The contract for IDisposable.Dispose indicates that it must be safe to call multiple times (calling Dispose on an object that was already disposed should do nothing)</li>\n<li>It can get very complicated to properly manage an inheritance hierarchy of disposable objects, especially if different layers introduce new Disposable and unmanaged resources.  In the pattern above Dispose(bool) is virtual to allow it to be overridden so that it can be managed, but I find it to be error-prone.</li>\n</ul>\n\n<p>In my opinion, it is much better to completely avoid having any types that directly contain both disposable references and native resources that may require finalization.  SafeHandles provide a very clean way of doing this by encapsulating native resources into disposable that internally provide their own finalization (along with a number of other benefits like removing the window during P/Invoke where a native handle could be lost due to an asynchronous exception).</p>\n\n<p>Simply defining a SafeHandle makes this Trivial:</p>\n\n<pre><code>\nprivate class SomeSafeHandle\n : SafeHandleZeroOrMinusOneIsInvalid {\n public SomeSafeHandle()\n  : base(true)\n  { }\n\n protected override bool ReleaseHandle()\n { return NativeMethods.CloseHandle(handle); }\n}\n</code></pre> \n\n<p>Allows you to simplify the containing type to:</p>\n\n<pre><code>\nclass SomeObject : IDisposable {\n SomeSafeHandle _SomeSafeHandle;\n FileStream _SomeFileStream;\n // Something useful here\n public virtual void Dispose() {\n  _SomeSafeHandle.Dispose();\n  _SomeFileStream.Dispose();\n }\n}\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/45036', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/234/']