Forum Moderators: open

Message Too Old, No Replies

Create objects on the fly?

Can it be done?

         

cococure

10:10 pm on Aug 11, 2003 (gmt 0)

10+ Year Member



Hi,

I've been looking all over for examples on how to do this, but haven't found anything useful.

I have created a class, something like this:

Class MyClass
...
class definitions
.....
End MyClass

I need to create instances of this class, but at any time when the page runs, I don't know ahead of time how many instances I will need. How do I dynamically create instances of this class (objects) and then be able to reference each instance?

Normally, I would do:

set myObject = new myClass

But is there such a thing as:

for i = 1 to 5

set myObject & i = new myClass

next

For a better idea conceptually of what I need, say I have a shopping cart object, with properties like totalNumberOfItems, subTotal, etc. I also have product objects with properties of productID, price, weight, etc.

Everytime a product is added into the shopping cart, I want to create a new product object, but how do I name and/or reference that object on the fly? That is what I don't quite get.

TIA

ziggystardust

9:57 am on Aug 12, 2003 (gmt 0)

10+ Year Member



Have you tried using one of the collection classes? I think an arraylist, which is more or less a dynamic array, would be pretty nice here. Sorry for the C# code...

ArrayList myArrayList = new ArrayList();

for (int i = 0; i < 5; i++) {
myArrayList.add(new MyClass());
}

If you want to read the arraylist, use count to get how many objects are in it:

MyClass tempObject;

for (int i = 0; i < myArrayList.Count; i++) {
tempObject = (MyClass)myArrayList[i];
}

Note that you have to do a cast since the arraylist stores everything just as "objects", that way, you can store different types of objects in the same arraylist (which isn't possible with a normal array).

Hope this helps

//ZS

cococure

7:34 pm on Aug 12, 2003 (gmt 0)

10+ Year Member



Yep that's it, however there aren't ArrayLists in VBScript, but it's still the same concept. Thanks!

Here is what I did in VBscript:

Class Package
....
define my class
.....
End Class

' Dynamic array
Dim arrPackages()

' array Index
Dim packageIndex
packageIndex = 0

' Every time I need to create a new object I do this:

Redim Preserve arrPackages(packageIndex)
set arrPackages(packageIndex) = New Package

' Iterate packageIndex
packageIndex = packageIndex + 1

Woo-hoo!
cococure

ziggystardust

9:43 pm on Aug 12, 2003 (gmt 0)

10+ Year Member



Hehe, thought this was asp.net! Glad it helped you anyway. ;)

//ZS

RossWal

11:57 pm on Aug 15, 2003 (gmt 0)

10+ Year Member



cococure,
How many of those buggers will you be creating? I understand Redim Preserve to be a notoriuosly costly operation. You might want to consider rediming lots of 10-20 at a time if you expect to dim bunches.

HTH

<edit>
Oh, just saw shopping cart. Unlikely you'll need to dim 20 at a time!
</edit>