0

I have a class called assetTransfer. If I have a loop and I create a new instance with the same name, what happens with the "old" one?

For i = 1 to 10
   Dim assetTransfer as New assetTransfer
next

Do I lose the previous instance?

Marcelo Gazzola
  • 907
  • 12
  • 28
  • Not sure if you lose it, but why would you want to do this? Seeing that it will more than likely result in undocumented/undesired behaviour – Luuklag Jun 18 '19 at 10:13
  • I need to create a new instance for this class and add it to a collection. the snippet above is only the first line. – Marcelo Gazzola Jun 18 '19 at 10:14
  • You don't need to declare a variable. You just add a new object to your collection. E.g my_collection.add new AssetTransfer – freeflow Jun 18 '19 at 10:22
  • Ok, removing the `Dim` then, what will happen with previous `assetTransfer` object – Marcelo Gazzola Jun 18 '19 at 10:26
  • In the loop you provide each time you go through the loop the previous creation will be overwritten by the new AssetTransfer assignment. – freeflow Jun 18 '19 at 10:30
  • Actually, in the instance above (and being quite specific) I don't think anything is being created. The same object is being DIMmed but it is not being set to an instance of the Class so nothing is ever created or destroyed. (Happy to be corrected). –  Jun 18 '19 at 10:55
  • You should read this: https://stackoverflow.com/a/42656772/10223558 Dim ... as new .... should be avoided in most cases. – L8n Jun 18 '19 at 11:13

1 Answers1

2

In your case specifically assetTransfer will never be instantiated, since it is never called. MS Docs

The dim foo as new bar statement should be avoided in most cases, instead use separate declaration and instantiation like: dim foo as bar and set foo = new bar Reason: What's the difference between Dim As New vs Dim / Set

A way to solve this would look like this.
At the end you have 10 instances of assetTransfer in your Collection

dim aCollection as Collection
set aCollection = new Collection
Dim assetTransferInstance as assetTransfer

For i = 1 to 10
   set assetTransferInstance = new assetTransfer
   'do something with assetTransfer
   aCollection.Add assetTransferInstance 
next i

debug.print aCollection.Count   '10
L8n
  • 728
  • 1
  • 5
  • 15
  • Thank you, is it the same of just `aCollection.Add New assetTransferInstance` and removing the line `set assetTransferInstance = new assetTransfer`? – Marcelo Gazzola Jun 18 '19 at 11:56
  • No, `assetTransferInstance` is a reference (something like a pointer), not something you would instantiate. I guess you what you meant is `aCollection.Add New assetTransfer` which would work (afaik). If it is just to save some lines of code I would not use this method. Especially if you want to use the object within the loop. – L8n Jun 18 '19 at 12:21