Reputation: 3
what I need does not seem to be too special, but somehow - maybe i am googling the wrong key words - I failed to find anything on the web.
How can I store variables (or references to them?) in Lists / Arrays / or something like that in a way that when I apply a change to the list the change will also be applied to the variable?
Something like:
Dim myList As New List(Of Object)
Dim a As Integer = 5
myList.Add(a)
myList(0) = 10 'here i want a to change as well
If a = 10 Then
'This is exactly what I want
Else If a = 5 Then
'This is what i don't want but what I will get
End If
So how can I accomplish this?
Upvotes: 0
Views: 201
Reputation: 460138
An integer is a value type, not a reference type like a class. You have two copies of that value, once in the list and once in the variable. If you want that behavior you needed to store a reference type in the list. For example:
Public Class MyNumber
Public Sub New(number As int32)
Value = Number
End Sub
Public Property Value As Int32
End Class
Sub Main
Dim myList As New List(Of MyNumber)
Dim myFirstNumber As New MyNumber(5)
myList.Add(myFirstNumber)
myList(0).Value = 10
' Now both, myFirstNumber.Value and myList(0).Value is 10
End Sub
Upvotes: 2