I would like to store references to a bunch of structs in a collection. The general scaffolding looks like this:
Structure myStructType
Dim prop1 as String
Dim prop2 as int
End Structure
Dim myList as new List(Of myStructType)()
'Wrongness below
Dim myStruct as new myStructType()
myStruct.prop1 = "struct1"
myStruct.prop2 = 1
myList.Add(myStruct)
myStruct = new myStructType()
mystruct.prop1 = "number two"
mystruct.prop2 = 2
myList.Add(myStruct)
now this doesn’t work, because it’s referencing the same memory. What I would really want is the ‘pass reference by value’ behaviour that is also used for reference types, so that I can easily keep producing more of them.
Is there any way to fix this other than to make the structs into classes? Is this actually a proper way to use structs, or do I have it all wrong?
This code does the same thing whether it is a struct or a class because you are invoking
new myStructType()for each object. That being said, be aware that later retrieving and modifiying those myStructType objects behave differently. If it is derrived froma structure then you are copying the data on a retrieve, leaving the original untouched in the list. If it is derrived from a class then you are getting a reference to that object and changes made using that reference change the instance in the list.I still wonder what you are trying to accomplish (or avoid) by using structures instead of classes?