If I set a variable using `CreateObject()`, do I need to clean it up by setting it to `Nothing` after use?

Nick Strupat picture Nick Strupat · Nov 16, 2011 · Viewed 23.4k times · Source

If I set a variable using CreateObject(), do I need to clean it up by setting it to Nothing after use?

Dim foo
Set foo = CreateObject("SomeAssembly")
foo Bar
Set foo = Nothing

I just found this post by Eric Lippert:

The script engine will automatically clear those variables when they go out of scope, so clearing them the statement before they go out of scope seems to be pointless.

Answer

Eric Lippert picture Eric Lippert · Nov 16, 2011

If I set a variable using CreateObject(), do I need to clean it up by setting it to Nothing after use?

Typically you do not, but it has become lore in the VB community that you do. If you are a supersitious person, it doesn't hurt to ward off the evil eye by setting variables to Nothing when you are done with them, but it rarely helps anything either.

The rare cases where you do need to set a variable to Nothing are those cases where:

  • you have created a circular reference that the garbage collector is unable to clean up
  • the object is expensive but the variable is long-lived, so you want it to be cleaned up early
  • the object implementation requires a particular shutdown order that must be maintained
  • and so on.

If I'm not in one of those cases, I don't set variables to Nothing. I've never had a problem with that.