Compound data type: Difference between revisions

Content added Content deleted
No edit summary
(→‎{{header|Visual Basic .NET}}: Expanded remarks about structure mutability)
Line 2,192: Line 2,192:
=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==


=== Simple Structures ===
=== Structures ===


This shows a structure in its simpest form.
A simple structure with two public, mutable fields:
<lang vbnet>Structure Point

<lang vbnet>Structure Simple_Point
Public X, Y As Integer
Public X, Y As Integer
End Structure</lang>
End Structure</lang>
Line 2,202: Line 2,201:
=== Immutable Structures ===
=== Immutable Structures ===


It is generally recommended in .NET that mutable structures only be used in niche cases where they provide needed performance, e.g. when the creation of massive numbers of class instances would cause excessive garbage collection pressure, as high-performance code dealing with structs generally is of a paradigm considered "impure" from an object-oriented perspective that relies on passing by reference and directly exposing fields.
In Visual Basic, mutable strucutures are difficult to use properly and should only be used when performance measurements warrant it. The rest of the time, immutable structures should be used. Below is the same structure seen before, but in an immutable form.


The semantics of value types in .NET mean that a new copy of a structure is created whenever one is passed by value to or from a method or property. This is particularly vexing when properties are involved, as it is not possible to mutate a structure that is returned by a property, due to the returned structure actually being an independent copy of whatever the property originally returned. The only workaround would be to store the value of the property in a temporary variable, mutate that variable, and assign the mutated variable back to the property, which involves another copy operation. When a structure is large, this copying can significantly affect performance.
<lang vbnet>Structure Immutable_Point
Private m_X As Integer
Private m_Y As Integer


On another note, algorithms relying on immutable data structures are often more easily parallelized, as they eliminate the race conditions caused by concurrent reading and writing.
Public Sub New(ByVal x As Integer, ByVal y As Integer)
m_X = x
m_Y = y
End Sub


Below is the same <code>Point</code> as above, except with an immutable API.
Public ReadOnly Property X() As Integer
Get
Return m_X
End Get
End Property


<lang vbnet>Structure ImmutablePoint
Public ReadOnly Property Y() As Integer
Get
ReadOnly Property X As Integer
ReadOnly Property Y As Integer
Return m_Y
End Get
End Property


Public Sub New(x As Integer, y As Integer)
Me.X = x
Me.Y = y
End Sub
End Structure</lang>
End Structure</lang>