Reputation: 117
I am working on a program that creates a linkedlist having a structure as nodes. At a certain point I need to change some values inside of a particular node (structure). Here is some code:
Structure tp
Dim a as double
Dim b as integer
End Structure
Sub main()
Dim lst as new LinkedList(of tp)
Dim node as tp
node.a = 10.1
node.b = 1
lst.addfirst(node)
'......
' Now I want to change the value of first node
lst.first.value.a = 2
' But I get "Expression is a value and therefore cannot be the target of an assignment."
End Sub
How do I perform such a modification?
Upvotes: 0
Views: 184
Reputation: 26434
The solution is simple - replace your structure with a class and adjust usage accordingly:
Class tp
Public a As Double
Public b As Integer
End Class
Sub main()
Dim lst As New LinkedList(Of tp)
Dim node As New tp
node.a = 10.1
node.b = 1
lst.AddFirst(node)
lst.First.Value.a = 2
End Sub
Problem was that structures are passed by value, unlike classes, so Value will return a copy of the object, rather than a copy of the reference to that object. In the down-on-earth terms it means you cannot change the original object. With a class, you can.
I would always recommend using classes, probably because I am more used to them, and so biased to recommend them. But if you decide to use a Structure, please make sure you are aware of the differences:
Upvotes: 2
Reputation: 2171
Your LinkedList
is of type tp
so its value is a tp
type object.
In order to change the value you have to provide a new structure:
dim newtp as tp
newtp.a = 2
newtp.b = lst.first.value.b
Then AddBefore
this newtp
and Remove
the old one.
Upvotes: 0