-
Referencing Object
what's the difference between
Code:
Dim objName as New ExistingObject
against
Dim objName as ExistingObject
Set objName = New ExistingObject
both are early binded, correct me f i'm wrong.
so would the first indicate a mature or professional way of coding or the second code maybe? could someone please advise me about some other difference between the two.
-
the difference is that in the first form (set as new), the vb runtime will instansiate the object every time it referenced even if u set it to nothing - that means the object variable is not totally removed but is still there somewhere in the memory.
in the latter case if u set the object to nothing, vb will actually release the object pointer.
consider the following code:
Dim obj As Widget
Set obj = New Widget
If obj Is Nothing Then
MsgBox "obj is nothing"
Else
MsgBox "obj is alive"
End If
Set obj = Nothing
If obj Is Nothing Then
MsgBox "obj is nothing"
Else
MsgBox "obj is alive"
End If
if u run that code u will get:
"obj is alive"
"obj is nothing"
this is reasonable outcome for most of the programmers.
now change the first two declaration lines to this line:
Dim obj As New Widget
and run it, ouch, this is not what i meant, didn't i?
this is very important to notice, that even if u check the object to if it's nothing (non call to methods or properties at all), vb quickly instansiate it back to live.
so if u have global objects in your application do not use Set As New at all, because if u will release that variables objects don't surprise if u suddenly watch them alive.
-
setting an object to nothing wasn't what i mean
what i need to understand is the difference b/n
Code:
Dim MyObject As New ExistingObject
and
Code:
Dim MyObject As ExistingObject
Set MyObject = New ExistingObject
-
i'm not sure u read my comment.
i emphasized the problems that can result from one way to another.
the statement:
Dim MyObject As New ExistingObject
cause the runtime to allocate memory for variable of type ExistingObject and also to create an object of that type.
at this statement:
Dim MyObject As ExistingObject
Set MyObject = New ExistingObject
vb create variable of the type ExistingObject, and then it create a real instance of the specified type.
in addition to my previous comment, the latter gives u more control over when the instance of the class are actually created.
suppose u have a global object, that you want to create only in some condition, so, u can just declare at the object in a module (or elsewhere), and actually create the object in other place (e.g. Class or function).
one more thing, when u use Set As New (the first form), it can slower performance, because vb create the object every time u reference it (one more time - EVEN if test it for nothing, or just call a property). so every time vb encounter that variable it must test weather or not an object reference has already been assigned to the variable.