By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,528 Members | 1,330 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,528 IT Pros & Developers. It's quick & easy.

call a variable with a variable

P: 2
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:

Expand|Select|Wrap|Line Numbers
  1. 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

Many thanks
Aug 27 '10 #1
Share this Question
Share on Google+
4 Replies

P: 320
I think you want the CallByName() function
Aug 28 '10 #2

P: 2
I've looked in to that but it appears not to work :S
Aug 28 '10 #3

P: 320
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

Expand|Select|Wrap|Line Numbers
  1.  Private Function MyVariable(ByVal s as String) as Object
  3. if s = "bla" then Return var1
  4. if s = "dude" then Return var2
  6. End Function
Aug 30 '10 #4

Joseph Martell
Expert 100+
P: 196
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:
Expand|Select|Wrap|Line Numbers
  1. Public Class TestClass2
  2.     Public Shared var1 As String
  3. End Class

This is how you can access var1 using reflection:

Expand|Select|Wrap|Line Numbers
  1. Dim myTestClass2 As New TestClass2()
  2. Dim myFieldInfo As FieldInfo = myTestClass2.GetType().GetField("var1")
  3. If (myFieldInfo IsNot Nothing) Then
  4.     myFieldInfo.SetValue(myTestClass2, "new value", BindingFlags.SetField, Nothing, Globalization.CultureInfo.InvariantCulture)
  5. End If
Aug 30 '10 #5

Post your reply

Sign in to post your reply or Sign up for a free account.