0

I often see code like:

If Not someThing = Nothing Then Set someThing = Nothing

And I also see comments that explicitly setting an object to Nothing is not absolutely necessary as the VBA garbage collector will do it anyway (especially true for locally declared objects, but apparently less so in some situations using MS Access).

But, notwithstanding the temptation to save a line of code and let the garbage collector do its thing...

Is there a reason for testing if someThing is Nothing before setting it to Nothing - does it make any difference whatsoever? I don't think it helps readability...

Why not just say: Set someThing = Nothing and be done with it?

SlowLearner
  • 3,086
  • 24
  • 54
  • 2
    VBA isn't garbage collected in the strictest sense of the term - it's reference counted. That said, your line of code does absolutely `Nothing`. – Comintern Oct 04 '18 at 00:52
  • @Comintern Tnx, so just set it to Nothing or don't bother at all and let the references count down? – SlowLearner Oct 04 '18 at 00:54
  • 2
    FWIW, [I never set anything to `Nothing`](https://blogs.msdn.microsoft.com/ericlippert/2004/04/28/when-are-you-required-to-set-objects-to-nothing/). – Comintern Oct 04 '18 at 00:57
  • 2
    There's no reason to do `Set foo = Nothing`, *even fewer* reasons to do it conditionally. Setting `Nothing` to `Nothing` is pure no-op code. – Mathieu Guindon Oct 04 '18 at 00:57
  • @MathieuGuindon I don't see how setting Nothing to Nothing became a point to make... but point taken. Re this being a duplicate... although this comes from a clearly flawed understanding, this question asked about the check - but semantics... – SlowLearner Oct 04 '18 at 01:11
  • 1
    The linked blog post is the best explanation I've run across. – Comintern Oct 04 '18 at 01:14
  • @Comintern - yes, thanks for sharing that good reading :) – SlowLearner Oct 04 '18 at 01:19
  • FWIW: In the link from @Comintern, interesting right here: *The garbage collector is going to pick one of them, and which one, we don't know. If these two objects have some complex interaction, and furthermore, one of the objects has a bug whereby it must be shut down before the other, then the scope finalizer might pick the wrong one!* – SlowLearner Oct 04 '18 at 01:28

0 Answers0