Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 233
Nick Strupat Avatar asked Nov 15 '11 23:11

Nick Strupat


People also ask

How do you create a variable for an object?

You assign an object to such a variable by placing the object after the equal sign ( = ) in an assignment statement or initialization clause.

What is an object variable?

An object variable is a name for a location in the computer's memory that holds a reference (or pointer) to an object. To use object variables in the Map window, declare and instantiate an object (as in the BeforeTransformation event). Then, create a reference to the object.


1 Answers

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.

like image 108
Eric Lippert Avatar answered Sep 30 '22 18:09

Eric Lippert