Ben Mate
Ben Mate

Reputation: 45

VB.NET Reference/point to a variable

I am aware that I can't dynamically refer to a variable (eg. 'var & var.Close()'). Can I somehow have a variable that can point to another variable by name?

My current code is (where func() requires an array):

Dim playerNum As String = “P1”
Select Case playerNum
  Case “P1”
    Func(P1(x, xx))
  Case “P2”
    Func(P2(x, xx))
  .........
End Select

Can something along these lines be done?

Dim playerNum As varNameRef = P1(,)
Func(playerNum(x, xx))

Really anything to stop so much repetition would be greatly appreciated. Cheers.

Upvotes: 3

Views: 5411

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460340

You can do this by reflection, but i would advise against for performance-, readability- and maintainabilty-reasons.

You could use Actions(Of T) if you really want, for example:

Class Player
    Public Name As String
End Class

Sub play(player As Player)
    Console.WriteLine(player.Name & " plays now")
End Sub

Create some players to demonstrate:

Dim playerList As New List(Of Player)
For i As Int32 = 1 To 10
    Dim p = New Player() With {.Name = "P" & i}
    playerList.Add(p)
Next

playerList.ForEach(AddressOf play)    

Upvotes: 1

Steven Doggart
Steven Doggart

Reputation: 43743

What you need is a reference type (class), instead of a value type (structure). For instance, if you created a class that stored your array as a property, like this:

Public Class PlayerData
    Public Data(10, 30) As Object
End Class

This also gives you the advantage of easily expanding the data that you store about each player. Then, you could reference the same PlayerData object with multiple variables:

Dim player1 As New PlayerData()
Dim player2 As New PlayerData()
Dim player As PlayerData = Nothing
Select Case playerNum
    Case “P1”
        player = player1
    Case “P2”
        player = player2
End Select
Func(player.Data(x, xx))

However, it would be even better yet to store them in a dictionary as key value pairs, such as:

Dim players As New Dictionary(Of String, PlayerData)()
players("P1") = New PlayerData()
players("P2") = New PlayerData()

Then, you could access you players like this:

Func(players(playerNum).Data(x, xx))

Upvotes: 1

Related Questions