Bugs wrote:
Does anyone have any recommendations on the best way to create multiple
instances of the same class when the final number of instances is unknown?
For example, I have a class and based on some user actions, I want to
create n number instances of those classes, which is obviously unknown
at compile time.
What is the easiest way to create and then manage these kinds of objects?
Using an array seems intuitive but it also seems like it might be more
difficult to manage if you want to add and delete objects.
Would it be best to maybe create a collection of the objects? If so,
how would I name those objects before adding them to the collection. Is
it possible to name an object instance based on a string literal? e.g.
Public Sub createMyNewClass(ByVal myStringLiteral as String)
Dim myStringLiteral As New myNewClass(myStringLiteral)
Except somehow the value of myStringLiteral is used as the object name,
not the name "myStringLiteral"?
Thanks!
You are mixing up variable names with references.
An object never has a name, but a reference variable that is used to
keep track of the object may have a name.
Example:
Dim sb As StringBuilder
This declares a reference variable that can reference a StringBuilder
object. The variable has a name, and it's type is a reference. It
doesn't contain any reference at this time, though.
sb = New StringBuilder()
Now we have created an object and assigned the reference to the
variable. The object doesn't have a name itself, but the reference
variable has the name "sb". We use the variable whenever we want to
access the object, so it's easy to think that the object has a name, but
it hasn't.
What you are trying to do when you want to use a string to name the
object, is to create variables dynamically. This is sometimes done in
scripting languages (mostly because the coder doesn't know how to do it
any other way), but it's not possible in a compiled language, as all
variable names are resolved at compile time.
There are different collections that you can use to keep references to
objects. You mentioned an array, which is fine if you know the number of
objects before you create the array. Otherwise there are many different
collections that you can use, like lists, dictionaries, queues and stacks.
--
Göran Andersson
_____
http://www.guffa.com