ProgrammingVB.NET Developer, Architect

Describe the features and proper usage of structures (Structure) in Visual Basic compared to classes (Class). What limitations exist in their application, and how do they differ from classes in terms of memory management and behavior?

Pass interviews with Hintsage AI assistant

Answer

In Visual Basic, structures are defined using the Structure keyword. They:

  • Are value types: located on the stack or inside other objects;
  • Do not support inheritance from other user-defined types (but can implement interfaces);
  • Cannot have parameterless constructors except for the default constructor outside the structure body;
  • Cannot be declared as MustInherit (abstract) or contain finalizers;
  • Are a good choice for small, immutable objects, saving heap memory.

Example

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

Limitations

  • Structures cannot inherit from each other, only from System.ValueType.
  • Only a parameterless automatic constructor is allowed.
  • Only interfaces are allowed for implementation.
  • If a structure contains reference members, caution is warranted due to potential copying and mutation nuances.

Trick Question

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.