Benno Grimm Benno Grimm - 1 year ago 44 Question

Create dynamic Variables from an Array

Ok, so i want to create dynamic Variables as Integer using the names from an Array. This is what I've tried so far:

Dim subjects as Array {"Math", "English", "German"} 'Three example names
Dim subjectsInt as New Dictionary(Of Integer) 'Throws error: Not enough arguments
Dim i as Integer

For i = 0 to 2
subjectsInt(subjects(i)) = 0 ' Trying to create a variable with the name of entry number i of the Array & and the starting value 0

Console.WriteLine(subjects(1) & ": ")
Dim input As String = Console.ReadLine()
subjectsInt = CInt(input)
Loop While subjectsInt = 0 Or subjectsInt > 100
Next i

in the end I want a result like this:

Math = 10 'random values between 1 and 100
English = 40
German = 90

I hope my question is clear enough, thanks in advance :)

Answer Source

You're quite right that there's not enough arguments. A dictionary, more specifically a Dictionary(Of TKey, TValue), takes an argument for the type of key and the type of value it is going to use.

As you want it to use your strings for lookup you would have to make the first type a String:

Dim subjectsInt As New Dictionary(Of String, Integer)

This will make you able to access the values by doing:

subjectsInt(<your string here>)

subjectsInt(subjects(0)) 'The first string (which is "Math") from the 'subjects' array.

Though you must be sure to add the key first, but you may only add it once:

subjectsInt.Add("Math", <your initial value here>)

'You may use strings any way you can access them, for example:
subjectsInt.Add(subjects(0), <your initial value here>)
subjectsInt.Add(subjects(i), <your initial value here>)

Then you should just be able to get/set it as you wanted:

subjectsInt(subjects(i)) = CInt(input)