Dim x as new / Set x = nothing

Bolek
12-13-2004, 03:56 PM
Hello,

can somebody explain to me the

dim x as new y
set x = nothing

stuff, please? I am pretty skilled at C++. Is it similar to the new/delete operators? Or does this increase some reference counters and the memory is freed by garbage collector sometimes later as in Java?

How is it with the lifecycle of objects declared with dim x as new? If I declare a local variable this way, will it be freed when I leave the procedure or will it stay allocated until I explicitely delete it? And what with variables global to a form? Will they be freed when I unload the form? Adn if a class object is a member of another class, will it be freed if the parent object is freed automatically?

Thanks for your response. I was unable to find good explanation of this. In VB manuals they simply use this syntax without explaining these things. That's why I like C++ better - you have to know more but you better understand what your program is doing.

MikeJ
12-13-2004, 04:53 PM
Here's the answer as I understand it.

Dim x As New y

y is a class. It starts a new instance of the class. If you have used C++/Java, you're probably familiar with these. :) The lifecycle basically is: it exists until you set it equal to nothing. That's where

Set x = Nothing

Comes into play - this removes it from memory, ending it's "life". Does this answer your question?

Flyguy
12-14-2004, 02:10 AM
One problem with the used declaration, the object will always exist even if you set it to Nothing.
Preferred syntax:

Dim x As y

Set x = New y
'
Set x = Nothing

Diurnal
12-14-2004, 07:29 AM
dim x as new yis know as auto instancing. As soon as this line of code is run, VB will create a new variable x with the properties and attributes of y. Auto-instancing variables can't be tested against the Nothing value. In fact, as soon as you use one and try to set it to nothing, VB relentlessly creates a new instance of the object. For this reason alone, it is generally not a good practice to instanciate an object this way. That is why Flyguy's approach is the best method as it allows you to remove the object from memory at will. If an object is created with the As New key word and is referenced in the code, it really will exist until the application ends.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum