Cis
Cis

Reputation: 1

Referencing value by variable name

Is it possible to obtain the content of a variable by referencing to its name. I have a bunch of variables like

Dim _tipoEntero As String = "^[0-9].$"
Dim _tipoTelefono As String = "^[0-9]{6}$"

and I'm trying to reference as something like

myValue = GetVariableValue("_tipo" + validationString)

Upvotes: 0

Views: 1636

Answers (2)

Muhammad
Muhammad

Reputation: 1340

The short answer for your question is "Yes" it is possible :

myValue = Me.GetType.GetField("_tipo" & validationString).GetValue(Me)

And we can make more effective :

myValue = Me.GetType.GetField("_tipo" & validationString, Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.IgnoreCase).GetValue(Me)

I set the binding flags to catch both public and private variables, and also ignoring the case sensitive of your search, so it doesn't matter you type "_tipo" or "_TiPo".

This is an answer for your question, but I didn't suggest you a better way to do your task.

Upvotes: 0

the_lotus
the_lotus

Reputation: 12748

You could use a Dictionary.

    Dim tipos As New Dictionary(Of String, String)

    tipos.Add("Entero", "^[0-9].$")
    tipos.Add("Telefono", "^[0-9]{6}$")

    myValue = tipo(validationString)

Upvotes: 3

Related Questions