Question Structure problem or bug

mcorbeel

Member
Joined
Feb 7, 2011
Messages
6
Location
Belgium Europe
Programming Experience
10+
I just discovered a very very strange vb.net behaviour, that I think might be a bug: In an app I wrote I use alot of structures to hold complex data in memory. I mean the structure has 10's or even 100's of variables and each variable can have a value, or the variable can be an array with several values. If I want to make a copy of a record I just use structure1=structure2 and the second structure has the same values as structure1, this is very easy. But here's the problem, only single dimensioned variables are copied, arrays are not, and even worse they seem to be single-instance. So if I change a value in the array of structure2 the same array in structure1 is changed.
Maybe it sounds complicated but I enclose a simple sample here:

Public Class Form1

Structure structureTest
Dim name As String
Dim integer_array() As Integer
End Structure

Private Sub Form1_Load(ByVal sender AsObject, ByVal e As System.EventArgs) Handles Me.Load
Dim x1 As New structureTest
ReDim x1.integer_array(0)

Dim x2 As structureTest = x1
x1.name =
"x1"
x1.integer_array(0) = 1
x2.name =
"x2"
x2.integer_array(0) = 2 'this apparantly not only sets x2.integer_array(0) to value '2' but also x1.integer_array(0)

Dim T As String = "x1 name: " & x1.name
T &= vbCrLf &
"x2 name: " & x2.name
T &= vbCrLf
T &= vbCrLf &
"x1 value: " & x1.integer_array(0) & " (should be 1)"
T &= vbCrLf & "x2 value: " & x2.integer_array(0)
MsgBox(T)

End
End Sub

End Class
 
Structures are value types and meant to represent a single value that is very small in size, see for example Choosing Between Classes and Structures
Another fundamental concept you need to understand about data types is this: Value Types and Reference Types

So your type should be a class, and it should implement IClonable interface where you in Clone method create the clone copy of it.
 
Back
Top