PDA

View Full Version : Variables declared with 'New' cannot be made Nothing!



shankar
01-24-2011, 07:37 AM
Hi,

I came across something I wasn't aware of till now. But it led to a bug, so let me share it with others.

Basically, when you declare a variable as a New object in a code or class module, it cannot be set to 'Nothing' later

for example,

Dim O1 as New ObjType1

Msgbox O1 is Nothing ' => false

Set O1 = Nothing

Msgbox O1 is Nothing ' => still false

However, if you do not use the 'New' keyword in the declaration, but use it in the code, then it works as expected:

Dim O1 as ObjType1

Msgbox O1 is Nothing ' => true

Set O1 = New ObjType1

Msgbox O1 is Nothing ' => false

Set O1 = Nothing

Msgbox O1 is Nothing ' => true

In the first case, I assumed that O1 will be made Nothing, but it doesn't happen. If O1 is a Collection, then it's elements are removed, but the collection itself still exists.

I had to remove the New Collection declaration from my Class header, but instead use the New statement in the Class_Initialize for it to work as expected.

shankar
01-24-2011, 07:55 AM
Another point is that, if the object declared as New in the header is set to Nothing, it will be a new object, and its Class_Initialize will be run.

Bob Phillips
01-24-2011, 08:01 AM
Auto-instancing an object like that is never a good idea IMO. As you have found, you lose a lot of control.