call a variable with a variable

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • lazypeople
    New Member
    • Aug 2010
    • 2

    call a variable with a variable

    I'm attempting to set a variable from a variable i've searched high and low and looked in many books but still to no avail. I guess i'm using the wrong keyword.

    I have many public variables like this:

    Code:
    Public Shared var1 As String
    i want to call them dynamically from a string something similar to this:

    "var1" = "data"

    I know in php you can use $$ to do a similar thing how do i do this in vb.net

    Many thanks
    Ben
  • yarbrough40
    Contributor
    • Jun 2009
    • 320

    #2
    I think you want the CallByName() function

    Comment

    • lazypeople
      New Member
      • Aug 2010
      • 2

      #3
      I've looked in to that but it appears not to work :S

      Comment

      • yarbrough40
        Contributor
        • Jun 2009
        • 320

        #4
        I see.. I believe I also tried to do this at one point. I don't believe it is possible. Maybe you could create a function that returns the variable you want based on some parameter. like

        Code:
         Private Function MyVariable(ByVal s as String) as Object
        
        if s = "bla" then Return var1
        if s = "dude" then Return var2
        
        End Function

        Comment

        • Joseph Martell
          Recognized Expert New Member
          • Jan 2010
          • 198

          #5
          Doing this is pretty complicated. Yarbrough40 has the most straight-forward way to accomplish your goal, but to reference a member by the name of the member as a string, you really have to use reflection.

          This is what reflection is really for. You are essentially trying to ask a class if it has a member called "blah" and if it does have that member, you want to set it. What is easy to do at design time is very complex to accomplish at run time.

          For a simple class such as:
          Code:
          Public Class TestClass2
              Public Shared var1 As String
          End Class

          This is how you can access var1 using reflection:

          Code:
          Dim myTestClass2 As New TestClass2()
          Dim myFieldInfo As FieldInfo = myTestClass2.GetType().GetField("var1")
          If (myFieldInfo IsNot Nothing) Then
              myFieldInfo.SetValue(myTestClass2, "new value", BindingFlags.SetField, Nothing, Globalization.CultureInfo.InvariantCulture)
          End If

          Comment

          Working...