Hamish Symington wrote:
Hello,
I'm trying to re-code a site which I wrote in PHP into
ASP.NET using Visual Basic .NET.
Something PHP has which has proved invaluable is the
concept of variable variables. I haven't had any success
with working out how to do it and hoped someone might be
able to help.
What I need to do is (for example)
Dim Foods(2) As String
Foods(0) = "Fish"
Foods(1) = "Chips"
Foods(2) = "Peas"
For Foods = 0 To 2
Dim [value of Foods(x)] As String
Next
So this would declare three variables as strings: called
Fish, Chips and Peas.
PHP is able to do this because as an interpreted language, the
'language engine' is available at runtime, so stuff like parsing can
happen at runtime. .NET languages are compiled, and as such at runtime
you aren't actually running VB any more, so the VB language engine is
not available.
However, don't worry, there is an easy 'Framework-y' way to achieve
what you want.
You want to: Create a list of arbitrary Strings (the 'variable names'),
and then attach a String value to each name (the 'variable values'). In
the Framework, this is exactly the functionality provided by
(implementers of) the IDictionary interface (quote from documentation):
The IDictionary class is the base interface for collections of
key-and-value pairs.
Each element is a key-and-value pair stored in a DictionaryEntry
object.
Each association must have a unique key that is not a null reference
(Nothing in Visual Basic), but the value of an association can be any
object reference, including a null reference (Nothing). The IDictionary
interface allows the contained keys and values to be enumerated, but it
does not imply any particular sort order.
(The data structure you want is also known as an *associative array*,
if that's any help)
Of the many built-in classes that implement IDictionary, the one I
would recommend to you here is the Hashtable (although I'm increasingly
thinking about using the HybridDictionary as my default IDictionary
implementation of choice). This is how you would use a Hashtable in
your scenario:
Dim Foods(2) As String
Foods(0) = "Fish"
Foods(1) = "Chips"
Foods(2) = "Peas"
' as before
Dim ht As Hashtable = New Hashtable()
For x = 0 To 2
ht.Add(Foods(x), "")
Next
Now you have three keys in the Hashtable, and thus you effectively have
three String variables ht("Fish"), ht("Chips"), ht("Peas"). You can
treat these as normal String variables from here on.
Of course there's much more to the Hashtable - both key and value can
be any object, not just Strings - but this is enough for the moment :)
--
Larry Lard
Replies to group please