0

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)
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Cis
  • 1
  • 2
  • I don't believe you can do that without using property's, [here](http://stackoverflow.com/questions/10338018/how-to-get-a-property-value-using-reflection) , Edit: while writing this i came up with [this](http://stackoverflow.com/questions/7649324/c-sharp-reflection-get-field-values-from-a-simple-class) – SomeNickName May 12 '15 at 15:55
  • 1
    Do those really need to be variables? If you are just associating names with strings, you could use a hash table. – Tony Hinkle May 12 '15 at 16:01
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders May 12 '15 at 17:43

2 Answers2

3

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)
the_lotus
  • 12,668
  • 3
  • 36
  • 53
  • 4
    Alternative: Store regex objects instead of strings. `Dim tipos As New Dictionary(Of String, Regex)` – Tomalak May 12 '15 at 15:58
0

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.

Top Systems
  • 951
  • 12
  • 24