Get value of variable named in a string

162 views Asked by At

Is there any way to get the value of a variable that has been named in a string. For instance:

Dim number As Integer = 12

Dim numberCopy As Integer = Convert("number")
' numberCopy will now equal 12
' Convert is the function to convert the string to the variable
2

There are 2 answers

1
Thomas Tempelmann On BEST ANSWER

Something like that can be done only with Introspection, and only if the variable holding the value is a property of a class. Your example, where the variable is only temporarily known inside a function, cannot be made work as you like.

To learn more about Introspection, see the documentation and examples of the same name.

0
Mitch Match On

You can also use a Dictionary instead of straight properties and variables.

For instance

   dim d as new dictionary
   d.value("number") = 12

Then when you need the value, you can do

   Dim numberCopy As Integer = d.value("number")

Nice thing about Dictionary is since keys as well as values are variant, you can throw at it pretty much anything, all variable types, as well as objects.

See Language Reference