-1

How can I "convert" a number to a variable name ?

Ok, so I receive from an external source over network, a number and a value. There are aprox 600 numbers. So now I need to put that value into a variable in my program. I could do with a long select-case where I look up the number, then store the sent value in the corresponding variable. Or, is there any other way ? Like storing all variable names in an array in the position that corresponds with the number, then get the var name from the array and set the received value to that variable ?

Sub WriteToMyVars(varNumber, val)
    Select varNumber
        Case "100"
            MyVarName1 = val
        Case "101"
            MyVarName2 = val
        Case "102"
            MyVarName3 = val
        'etc etc
    End Select
End Sub

'or -----------------------------------

Dim a(600) As String
a(100) = "MyVarName1"
a(101) = "MyVarName2"
a(102) = "MyVarName2"
'etc etc

Sub WriteToMyVars(varNumber, val)
    a(varNumber) = val 'this won't work I know, it'll put the val in the array instead of the varname, but something like this would be way shorter than the above
End Sub
  • 3
    Are maybe looking for a [Dictionary](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=net-7.0)? – Filburt May 26 '23 at 13:39

1 Answers1

0

Maybe you want a Hashtable?

Dim a As New Hashtable
a(varNumber) = val

Alternatively, as Filburt mentioned, you could use a Dictionary if you know the data types. The Dictionary is faster, and supersedes the Hashtable. If varNumber is an integer and val is a string then it would be:

Dim a As New Dictionary(Of Integer, String)
a.Add(varNumber, val)

The differences are discussed in this thread: .NET HashTable Vs Dictionary - Can the Dictionary be as fast?

Michael Foster
  • 420
  • 6
  • 12
  • I'd recommend against using a `Hashtable` for anything aside from legacy code, because it stores everything as `Object` so it requires casts to convert back to the original type. – Craig May 30 '23 at 17:46
  • @Craig, a valid point. Can you tell me what data type `val` is that the `Dictionary` should use in this case? – Michael Foster May 30 '23 at 18:44