ProgrammingVB/VB.NET Developer

How to implement User-Defined Types (UDTs) in Visual Basic, and when should they be used instead of classes?

Pass interviews with Hintsage AI assistant

Answer

In Visual Basic, user-defined types (Type in VB6 or Structure in VB.NET) allow you to define your own composite types that include multiple variables of different types. This is convenient for packaging related data.

UDTs (VB6):

Type Person Name As String Age As Integer Height As Single End Type Dim employee As Person employee.Name = "Alexey" employee.Age = 32 employee.Height = 1.85

Structures (VB.NET):

Structure Person Public Name As String Public Age As Integer Public Height As Single End Structure Dim employee As Person employee.Name = "Alexey"

When to use:

  • For lightweight data containers without logic
  • When performance is important (structures are created on the stack)
  • If inheritance functionality is not needed — structures do not support inheritance

Conversely: Classes are used when encapsulation of logic, inheritance, polymorphism, or interface implementation is needed.

Trick Question

Why can't structures in VB.NET be assigned Nothing?

Answer: Only class variables (objects) can be assigned Nothing since they hold references. Structures are value types; they always contain a set of values; attempting to assign Nothing will result in a compilation error.

Dim s As Person = Nothing 'Error! Structures cannot be Nothing (except Nullable(Of T))

Examples of real errors due to ignorance of topic nuances


Story

In an old project, it was decided to replace an array of primitives with a structure containing several fields, but the new code unexpectedly became slower. It turned out: the structure was very large in size and was frequently copied into functions. If a class had been used, only references would have been copied, not the whole structure.


Story

After porting a VB6 UDT to VB.NET, one of the developers did not implement the ISerializable interface for the structure in a remote call. As a result, the remote object could not be serialized, causing failures during inter-process communication.


Story

In a module for working with geometry, the structure held references to arrays (mutable). Multiple instances of this structure led to unexpected effects, as inside the structure the references pointed to the same data arrays — mutations were reflected across all copies!