I am working on a web application and I have run into the following situation.
Dim a as Object Dim i as Integer = 0 Try For i=1 to 5 a = new Object() 'Do stuff ' a = Nothing Next Catch Finally a = Nothing End Try
Do i need to do the a=Nothing in the loop or will the garbage collector clean a up?
In .NET, you generally do not need to set a variable reference =
Nothing(nullin C#). The garbage collector will clean up, eventually. The reference itself will be destroyed when it goes out of scope (either when your method exits or when the object of this class is finalized.) Note that this doesn’t mean the object is destroyed, just the reference to it. The object will still be destroyed non-deterministically by the collector.However, setting your reference =
Nothingwill provide a hint to .NET that the object may be garbage, and doesn’t necessarily hurt anything — aside from code clutter. If you were to keep it in there, I’d recommend removing it fromTryblock; it’s already in theFinallyblock and will therefore always be called. (Aside from certain catastrophic exceptions; but in those cases it wouldn’t get called in theTryblock either!)Finally, I have to admit that I agree with Greg: Your code would be cleaner without this. The hint to the runtime that you’re done with the reference is nice, but certainly not critical. Honestly, if I saw this in a code review, I’d probably have the developer rewrite it thusly: