0

In javascript I can do

var thing="MyVar";
var MyVar;
this[thing] = 33;

to set the value of a variable based on another value. So in this case it sets the value 33 to the value of the variable thing.

edit- This will then set the value of MyVar to 33, if I had another value in thing say otherVar it would set the value of otherVar to be 33!

Is there any way to do this in VB.Net?

4
  • you could use the clay project. Commented Dec 5, 2014 at 14:13
  • 1
    Have a look here and here Commented Dec 5, 2014 at 14:25
  • 1
    Use Dictionary(Of String, Integer) in vb.net Commented Dec 5, 2014 at 14:31
  • See Value Types and Reference Types based on current edit Commented Dec 5, 2014 at 14:34

1 Answer 1

0

Here's an example using Reflection in WinForms that will work with Fields or Properties:

Public Class Form1

    Private MyVar As Integer

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim thing As String = "MyVar"
        Dim value As Integer = 33
        Try
            Dim FI As System.Reflection.FieldInfo = Me.GetType.GetField(thing, Reflection.BindingFlags.IgnoreCase Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic)
            If Not IsNothing(FI) Then
                FI.SetValue(Me, value)
            Else
                Dim PI As System.Reflection.PropertyInfo = Me.GetType.GetProperty(thing, Reflection.BindingFlags.IgnoreCase Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic)
                If Not IsNothing(PI) Then
                    PI.SetValue(Me, value)
                Else
                    MessageBox.Show(value, "Field or Property not found!")
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Unable to Set Value")
        End Try

        Debug.Print("MyVar = " & MyVar)
    End Sub

End Class

If you're using this, though, you probably have a bad design to your application.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.