In Visual Basic, structures are defined using the Structure keyword. They:
MustInherit (abstract) or contain finalizers;Public Structure Point Public X As Integer Public Y As Integer Public Sub New(x As Integer, y As Integer) Me.X = x Me.Y = y End Sub End Structure Dim p1 As New Point(1, 2) Dim p2 = p1 ' Value is copied, not reference! p2.X = 5 ' p1.X = 1, p2.X = 5
Q: How does a structure behave when passed to a function ByVal and ByRef? What is the difference from passing a class?
A: When passing a structure ByVal, a copy of the entire structure is created. Changes in the function do not affect the original. With ByRef — the original variable is modified. Unlike classes, which pass a reference when passed (even ByVal), structures are fully copied in ByVal, affecting performance and behavior.
Sub MutateByVal(p As Point) p.X = 100 End Sub Sub MutateByRef(ByRef p As Point) p.X = 100 End Sub Dim s As New Point(3, 4) MutateByVal(s) ' s.X is still 3 MutateByRef(s) ' s.X is now 100
History
1. In a large library project, structures were used to pass large arrays of data through ByVal interfaces. This resulted in performance degradation due to multiple copies of large structures on the stack. The problem was solved by replacing structures with immutable classes.
History
2. In a GIS development project, confusion arose when copying structures containing reference fields — by modifying an array inside the structure, the developer did not expect that the original would change everywhere the array was copied, despite being a “value type.”
History
3. In accounting software, structures were mixed with classes for business entities: trying to implement inheritance for a structure resulted in a compilation error, necessitating a reorganization of the system architecture, which turned out to be labor-intensive due to the initially incorrect choice between structures and classes.