Question Possible to instantiate object from class using string variable for name of new obj?

Lumirris

New member
Joined
Aug 11, 2009
Messages
2
Programming Experience
Beginner
Let me preface by saying that I am new to programming, and my knowledge is spotty, so I'm not even sure what to call what it is that I'm trying to do:

dim myCollection as new Specialized.StringCollection
dim myFoundThings as new ArrayList
dim index as Integer
dim newResultMemberName as String

For Index = 0 To (myCollection.Count - 1)


If myCollection(Index) = "YouFoundMe" Then

newResultMemberName = myCollection(Index) & Index.ToString
' This is the part I'm not sure about - basic idea on following line:
' Dim <literal value of newResultMemberName> as New ThingFound(myCollection(index), Index)
myFoundThings.Add(<literal value of newResultMemberName>)
End If
Next Index

Public Class ThingFound

Public Sub New(ByVal contents As String, ByVal index As Integer)

' Assign constructors to ReadOnly Properties (I know how to do this part)
End Sub
End Class

This is part of some code that will run without user interaction once it's spinning away, and I need to create a unique object from some items found in a StringCollection, naming the objects using information found in the strings stored in that StringCollection.

Is this possible? Is this possible for a project targeted at .NET 2.0? Is there a better way to approach this problem?

Thanks in advance for any advice!
 
A variable name doesn't have the meaning you think. It's all about references, and variables is merely temporary placeholders for various things, next iteration the variable may refer to a different object, or nothing at all. Variables are named conveniently for readability of code, but the variables are NOT the objects the point to. What you should do if you want to name an instance of the Thing class is to give it a Name property. If you want to keep objects created you have to keep a collection of the object references.
VB.NET:
Dim things As New List(Of Thing)
For i As Integer = 1 To 10
    Dim tmp As New Thing
    tmp.Name = "Thing" & i.ToString
    things.Add(tmp)
Next
You see?

Another possibility is if the string reference it unique, then you can link it using a Dictionary loopup table like this:
VB.NET:
Dim things As New Dictionary(Of String, Thing)
For i As Integer = 1 To 10
    Dim tmp As New Thing
    tmp.Name = "Thing" & i.ToString
    things.Add(tmp.Name, tmp)
Next
Dim someThing As Thing = things("Thing5")
The someThing variable would here refer to the Thing instance whose Name property incidentally also was set to "Thing5".
 
Back
Top