Dim as New

R

Rob Richardson

Greetings!

I am an experienced VB6 user just getting into the VB .Net world. In VB6,
many people frowned on the use of "Dim x As New MyObject" because it could
produce unexpected results, such as the following:

Dim X as New MyObject
Set X = Nothing
If X Is Nothing Then
MsgBox "X has been destroyed"
Else
MsgBox "Why the heck is X still here?"
EndIf

In the above VB6 code, X is recreated in the If statement because of the use
of Dim as New, and the second message box appears. Does VB.Net behave the
same way?

Thanks!

Rob
 
C

Codemonkey

Does VB.Net behave the same way?

Nope. In VB.net, all of the following produce the same result:

1)
------------------
Dim X as New Object
-----------------

2)
--------------------
Dim X as Object = New Object()
-------------------

3)
-------------------
Dim X as Object
X = New Object()
-------------------

(obviously you have to create a specific object type, not just "object")

HTH,

Trev.
 
H

Herfried K. Wagner [MVP]

* "Rob Richardson said:
I am an experienced VB6 user just getting into the VB .Net world. In VB6,
many people frowned on the use of "Dim x As New MyObject" because it could
produce unexpected results, such as the following:

Dim X as New MyObject
Set X = Nothing
If X Is Nothing Then
MsgBox "X has been destroyed"
Else
MsgBox "Why the heck is X still here?"
EndIf

In the above VB6 code, X is recreated in the If statement because of the use
of Dim as New, and the second message box appears. Does VB.Net behave the
same way?

No. This behavior doesn't exist any more. There is no difference
between

\\\
Dim f As New Foo()
///

and

\\\
Dim f As Foo
f = New Foo()
///
 
J

Jay B. Harlow [MVP - Outlook]

Trev,
(obviously you have to create a specific object type, not just "object")
However it is useful to create a new object, literally "new object"
sometimes.

I will use them as a 'padlock' the object to which I SyncLock on.

Private Readonly m_padlock As New Object

SyncLock m_padlock
End SyncLock

The first couple times I saw the above, its "what! you can't do that", then
trying it, its like "cool!".

The other place I've seen it is when you need reference identity, but do not
need a specific value.

Public Readonly Red As New Object
Public Readonly Blue As New Object
Public Readonly Green As New Object

Red, Blue & Green are distinct values, however their value has no meaning.
You can simply use the "Is" operator to see if you have that reference. I
don't have a handy example of using this...

Hope this helps
Jay
 
C

Codemonkey

Nice one, Jay. I never tried that before. Cheers for the tip.

(note to self: build and test my suggestions to weed out stupid bugs before
posting ;)

Trev.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top