<p>Should you set all the objects to <code>null</code> (<code>Nothing</code> in VB.NET) once you have finished with them? </p>

<p>I understand that in .NET it is essential to dispose of any instances of objects that implement the <code>IDisposable</code> interface to release some resources although the object can still be something after it is disposed (hence the <code>isDisposed</code> property in forms), so I assume it can still reside in memory or at least in part?</p>

<p>I also know that when an object goes out of scope it is then marked for collection ready for the next pass of the garbage collector (although this may take time).</p>

<p>So with this in mind will setting it to <code>null</code> speed up the system releasing the memory as it does not have to work out that it is no longer in scope and are they any bad side effects?</p>

<p>MSDN articles never do this in examples and currently I do this as I cannot 
see the harm. However I have come across a mixture of opinions so any comments are useful.</p>

[{'answer_id': 2794, 'author': 'GateKiller', 'author_id': 383, 'author_profile': 'https://Stackoverflow.com/users/383', 'pm_score': -1, 'selected': False, 'text': '<p>Some object suppose the <code>.dispose()</code> method which forces the resource to be removed from memory.</p>\n'}, {'answer_id': 2797, 'author': 'Karl Seguin', 'author_id': 34, 'author_profile': 'https://Stackoverflow.com/users/34', 'pm_score': 4, 'selected': False, 'text': '<p>No don\'t null objects. You can check out <a href="https://web.archive.org/web/20160325050833/http://codebetter.com/karlseguin/2008/04/28/foundations-of-programming-pt-7-back-to-basics-memory/" rel="nofollow noreferrer">https://web.archive.org/web/20160325050833/http://codebetter.com/karlseguin/2008/04/28/foundations-of-programming-pt-7-back-to-basics-memory/</a> for more information, but setting things to null won\'t do anything, except dirty your code.</p>\n'}, {'answer_id': 2807, 'author': 'Bob', 'author_id': 45, 'author_profile': 'https://Stackoverflow.com/users/45', 'pm_score': 3, 'selected': False, 'text': '<p>The only time you should set a variable to null is when the variable does not go out of scope and you no longer need the data associated with it. Otherwise there is no need.</p>\n'}, {'answer_id': 2813, 'author': 'Steve T', 'author_id': 415, 'author_profile': 'https://Stackoverflow.com/users/415', 'pm_score': 3, 'selected': False, 'text': '<p>Also:</p>\n\n<pre><code>using(SomeObject object = new SomeObject()) \n{\n  // do stuff with the object\n}\n// the object will be disposed of\n</code></pre>\n'}, {'answer_id': 2821, 'author': 'Patrick', 'author_id': 429, 'author_profile': 'https://Stackoverflow.com/users/429', 'pm_score': 1, 'selected': False, 'text': "<p>There are some cases where it makes sense to null references. For instance, when you're writing a collection--like a priority queue--and by your contract, you shouldn't be keeping those objects alive for the client after the client has removed them from the queue. </p>\n\n<p>But this sort of thing only matters in long lived collections. If the queue's not going to survive the end of the function it was created in, then it matters a whole lot less.</p>\n\n<p>On a whole, you really shouldn't bother. Let the compiler and GC do their jobs so you can do yours.</p>\n"}, {'answer_id': 2839, 'author': 'Kev', 'author_id': 419, 'author_profile': 'https://Stackoverflow.com/users/419', 'pm_score': 7, 'selected': True, 'text': '<p>Karl is absolutely correct, there is no need to set objects to null after use. If an object implements <code>IDisposable</code>, just make sure you call <code>IDisposable.Dispose()</code> when you\'re done with that object (wrapped in a <code>try</code>..<code>finally</code>, or, a <code>using()</code> block). But even if you don\'t remember to call <code>Dispose()</code>, the finaliser method on the object should be calling <code>Dispose()</code> for you.</p>\n\n<p>I thought this was a good treatment:</p>\n\n<blockquote>\n  <p><a href="http://web.archive.org/web/20090311003201/http://msdn.microsoft.com/en-us/magazine/cc163392.aspx" rel="noreferrer">Digging into IDisposable</a></p>\n</blockquote>\n\n<p>and this  </p>\n\n<blockquote>\n  <p><a href="http://web.archive.org/web/20090426210049/www.marcclifton.com/tabid/79/Default.aspx" rel="noreferrer">Understanding IDisposable</a></p>\n</blockquote>\n\n<p>There isn\'t any point in trying to second guess the GC and its management strategies because it\'s self tuning and opaque. There was a good discussion about the inner workings with Jeffrey Richter on Dot Net Rocks here: <a href="http://www.dotnetrocks.com/default.aspx?showNum=361" rel="noreferrer">Jeffrey Richter on the Windows Memory Model</a> and\nRichters book <a href="http://amzn.eu/d/aitTG0A" rel="noreferrer">CLR via C#</a> chapter 20 has a great treatment: </p>\n'}, {'answer_id': 6728, 'author': 'dbkk', 'author_id': 838, 'author_profile': 'https://Stackoverflow.com/users/838', 'pm_score': 3, 'selected': False, 'text': "<p>In general, there's no need to null objects after use, but in some cases I find it's a good practice.</p>\n\n<p>If an object implements IDisposable and is stored in a field, I think it's good to null it, just to avoid using the disposed object. The bugs of the following sort can be painful:</p>\n\n<pre><code>this.myField.Dispose();\n// ... at some later time\nthis.myField.DoSomething();\n</code></pre>\n\n<p>It's good to null the field after disposing it, and get a NullPtrEx right at the line where the field is used again. Otherwise, you might run into some cryptic bug down the line (depending on exactly what DoSomething does).</p>\n"}, {'answer_id': 6739, 'author': 'mbillard', 'author_id': 810, 'author_profile': 'https://Stackoverflow.com/users/810', 'pm_score': 3, 'selected': False, 'text': '<p>Chances are that your code is not structured tightly enough if you feel the need to <em><code>null</code></em> variables.</p>\n\n<p>There are a number of ways to limit the scope of a variable:</p>\n\n<p>As mentioned by <strong>Steve Tranby</strong></p>\n\n<pre><code>using(SomeObject object = new SomeObject()) \n{\n  // do stuff with the object\n}\n// the object will be disposed of\n</code></pre>\n\n<p>Similarly, you can simply use curly brackets:</p>\n\n<pre><code>{\n    // Declare the variable and use it\n    SomeObject object = new SomeObject()\n}\n// The variable is no longer available\n</code></pre>\n\n<p>I find that using curly brackets without any "heading" to really clean out the code and help make it more understandable.</p>\n'}, {'answer_id': 12301, 'author': 'Wilka', 'author_id': 1367, 'author_profile': 'https://Stackoverflow.com/users/1367', 'pm_score': 5, 'selected': False, 'text': '<p>Another reason to avoid setting objects to null when you are done with them is that it can actually keep them alive for longer. </p>\n\n<p>e.g.</p>\n\n<pre><code>void foo()\n{\n    var someType = new SomeType();\n    someType.DoSomething();\n    // someType is now eligible for garbage collection         \n\n    // ... rest of method not using \'someType\' ...\n}\n</code></pre>\n\n<p>will allow the object referred by someType to be GC\'d after the call to "DoSomething" but</p>\n\n<pre><code>void foo()\n{\n    var someType = new SomeType();\n    someType.DoSomething();\n    // someType is NOT eligible for garbage collection yet\n    // because that variable is used at the end of the method         \n\n    // ... rest of method not using \'someType\' ...\n    someType = null;\n}\n</code></pre>\n\n<p>may sometimes keep the object alive until the end of the method. The <a href="http://blogs.msdn.com/clyon/archive/2004/12/01/273144.aspx" rel="noreferrer">JIT will usually optimized away the assignment to null</a>, so both bits of code end up being the same.</p>\n'}, {'answer_id': 13516, 'author': 'Scott Dorman', 'author_id': 1559, 'author_profile': 'https://Stackoverflow.com/users/1559', 'pm_score': 1, 'selected': False, 'text': '<p>Take a look at this article as well: <a href="http://www.codeproject.com/KB/cs/idisposable.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/cs/idisposable.aspx</a></p>\n\n<p>For the most part, setting an object to null has no effect. The only time you should be sure to do so is if you are working with a "large object", which is one larger than 84K in size (such as bitmaps).</p>\n'}, {'answer_id': 10098611, 'author': 'KenF', 'author_id': 337868, 'author_profile': 'https://Stackoverflow.com/users/337868', 'pm_score': 2, 'selected': False, 'text': '<p>this kind of "there is no need to set objects to null after use" is not entirely accurate.  There are times you need to NULL the variable after disposing it.</p>\n\n<p>Yes, you should ALWAYS call <code>.Dispose()</code> or <code>.Close()</code> on anything that has it when you are done.  Be it file handles, database connections or disposable objects.</p>\n\n<p>Separate from that is the very practical pattern of LazyLoad.</p>\n\n<p>Say I have and instantiated <code>ObjA</code> of <code>class A</code>.  <code>Class A</code> has a public property called <code>PropB</code> of <code>class B</code>.</p>\n\n<p>Internally, <code>PropB</code> uses the private variable of <code>_B</code> and defaults to null.  When <code>PropB.Get()</code> is used, it checks to see if <code>_PropB</code> is null and if it is, opens the resources needed to instantiate a <code>B</code> into <code>_PropB</code>.  It then returns <code>_PropB</code>.</p>\n\n<p>To my experience, this is a really useful trick.</p>\n\n<p>Where the need to null comes in is if you reset or change A in some way that the contents of <code>_PropB</code> were the child of the previous values of <code>A</code>,  you will need to Dispose AND null out <code>_PropB</code> so LazyLoad can reset to fetch the right value IF the code requires it.</p>\n\n<p>If you only do <code>_PropB.Dispose()</code> and shortly after expect the null check for LazyLoad to succeed, it won\'t be null, and you\'ll be looking at stale data.  In effect, you must null it after <code>Dispose()</code> just to be sure.</p>\n\n<p>I sure wish it were otherwise, but I\'ve got code right now exhibiting this behavior after a <code>Dispose()</code> on a <code>_PropB</code> and outside of the calling function that did the Dispose (and thus almost out of scope), the private prop still isn\'t null, and the stale data is still there.</p>\n\n<p>Eventually, the disposed property will null out, but that\'s been non-deterministic from my perspective.</p>\n\n<p>The core reason, as dbkk alludes is that the parent container (<code>ObjA</code> with <code>PropB</code>) is keeping the instance of <code>_PropB</code> in scope, despite the <code>Dispose()</code>.</p>\n'}, {'answer_id': 10188102, 'author': 'Munish Goyal', 'author_id': 520348, 'author_profile': 'https://Stackoverflow.com/users/520348', 'pm_score': 3, 'selected': False, 'text': '<p>In general no need to set to null. But suppose you have a Reset functionality in your class.</p>\n\n<p>Then you might do, because you do not want to call dispose twice, since some of the Dispose may not be implemented correctly and throw System.ObjectDisposed exception.</p>\n\n<pre><code>private void Reset()\n{\n    if(_dataset != null)\n    {\n       _dataset.Dispose();\n       _dataset = null;\n    }\n    //..More such member variables like oracle connection etc. _oraConnection\n }\n</code></pre>\n'}, {'answer_id': 37139504, 'author': 'John', 'author_id': 1978080, 'author_profile': 'https://Stackoverflow.com/users/1978080', 'pm_score': 0, 'selected': False, 'text': '<p>I believe by design of the GC implementors, you can\'t <b>speed up</b> GC with nullification. I\'m sure they\'d prefer you not worry yourself with how/when GC runs -- treat it like this ubiquitous <b>Being</b> protecting and watching over and out for you...(bows head down, raises fist to the sky)...</p>\n\n<p>Personally, I often explicitly set variables to null when I\'m done with them as a form of self documentation.  I don\'t declare, use, then set to null later -- I null immediately after they\'re no longer needed. I\'m saying, explicitly, "I\'m officially done with you...be gone..."</p>\n\n<p>Is nullifying necessary in a GC\'d language? No. Is it helpful for the GC? Maybe yes, maybe no, don\'t know for certain, by design I really can\'t control it, and regardless of today\'s answer with this version or that, future GC implementations could change the answer beyond my control. Plus if/when nulling is optimized out it\'s little more than a fancy <i>comment</i> if you will.  </p>\n\n<p>I figure if it makes my intent clearer to the next poor fool who follows in my footsteps, and if it <i>"might"</i> potentially help GC sometimes, then it\'s worth it to me. Mostly it makes me feel tidy and clear, and Mongo likes to feel tidy and clear. :)</p>\n\n<p>I look at it like this: Programming languages exist to let people give other people an idea of intent and a compiler a job request of what to do -- the compiler converts that request into a different language (sometimes several) for a CPU -- the CPU(s) could give a hoot what language you used, your tab settings, comments, stylistic emphases, variable names, etc. -- a CPU\'s all about the bit stream that tells it what registers and opcodes and memory locations to twiddle.  Many things written in code don\'t convert into what\'s consumed by the CPU in the sequence we specified.  Our C, C++, C#, Lisp, Babel, assembler or whatever is theory rather than reality, written as a statement of work.  What you see is not what you get, yes, even in assembler language. </p>\n\n<p>I do understand the mindset of "unnecessary things" (like blank lines) "are nothing but noise and clutter up code." That was me earlier in my career; I totally get that. At this juncture I lean toward that which makes code clearer. It\'s not like I\'m adding even 50 lines of "noise" to my programs -- it\'s a few lines here or there. </p>\n\n<p>There are exceptions to any rule. In scenarios with volatile memory, static memory, race conditions, singletons, usage of "stale" data and all that kind of rot, that\'s different: you NEED to manage your own memory, locking and nullifying as apropos because the memory is not part of the GC\'d Universe -- hopefully everyone understands that. The rest of the time with GC\'d languages it\'s a matter of style rather than necessity or a guaranteed performance boost.</p>\n\n<p>At the end of the day make sure you understand what is eligible for GC and what\'s not; lock, dispose, and nullify appropriately; wax on, wax off; breathe in, breathe out; and for everything else I say: If it feels good, do it. Your mileage may vary...as it should...</p>\n'}, {'answer_id': 55368215, 'author': 'Ebleme', 'author_id': 4082334, 'author_profile': 'https://Stackoverflow.com/users/4082334', 'pm_score': 2, 'selected': False, 'text': '<p>Stephen Cleary explains very well in this post: <a href="https://blog.stephencleary.com/2010/02/q-should-i-set-variables-to-null-to.html" rel="nofollow noreferrer">Should I Set Variables to Null to Assist Garbage Collection?</a></p>\n\n<p>Says: </p>\n\n<blockquote>\n  <p>The Short Answer, for the Impatient\n  Yes, if the variable is a static field, or if you are writing an enumerable method (using yield return) or an asynchronous method (using async and await). Otherwise, no.</p>\n  \n  <p>This means that in regular methods (non-enumerable and non-asynchronous), you do not set local variables, method parameters, or instance fields to null.</p>\n  \n  <p>(Even if you’re implementing IDisposable.Dispose, you still should not set variables to null).</p>\n</blockquote>\n\n<p>The important thing that we should consider is <strong>Static Fields</strong>.</p>\n\n<blockquote>\n  <p><strong>Static fields are always root objects</strong>, so they are <strong>always considered “alive”</strong> by the garbage collector. If a static field references an object that is no longer needed, it should be set to null so that the garbage collector will treat it as eligible for collection.</p>\n  \n  <p>Setting static fields to null is meaningless if the entire process is shutting down. The entire heap is about to be garbage collected at that point, including all the root objects.</p>\n</blockquote>\n\n<p>Conclusion:</p>\n\n<blockquote>\n  <p><strong>Static fields</strong>; that’s about it. Anything else is a <strong>waste of time</strong>.</p>\n</blockquote>\n'}, {'answer_id': 57921316, 'author': 'Thulani Chivandikwa', 'author_id': 611628, 'author_profile': 'https://Stackoverflow.com/users/611628', 'pm_score': 0, 'selected': False, 'text': '<p>I think setting something back to null is messy. Imagine a scenario where the item being set to now is exposed say via property. Now is somehow some piece of code accidentally uses this property after the item is disposed you will get a null reference exception which requires some investigation to figure out exactly what is going on.</p>\n\n<p>I believe framework disposables will allows throw ObjectDisposedException which is more meaningful. Not setting these back to null would be better then for that reason.</p>\n'}]
['https://Stackoverflow.com/questions/2785', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/33/']