STRUCTURE INSTANTIATION DETAILS

Structures handle instantiation somewhat differently from object references. When you declare a reference variable, Visual Basic does not automatically allocate the object to which the variable points. In contrast, when you declare a value type such as a structure, Visual Basic automatically allocates space for the variable’s data. That means you never need to use the New keyword to instantiate a structure.

However, the Visual Basic compiler warns you if you do not explicitly initialize a structure variable before using it. To satisfy the compiler, you can use the New keyword to initialize the variable when you declare it.

A structure can also provide constructors, and you can use those constructors to initialize the structure. The following code defines the SPerson structure and gives it a constructor that takes two parameters, the second optional:

Public Structure SPerson
    Public FirstName As String
    Public LastName As String
 
    Public Sub New(
     ByVal first_name As String,
     Optional ByVal last_name As String = "<unknown>")
        FirstName = first_name
        LastName = last_name
    End Sub
End Structure

To use a structure’s constructor, you initialize the structure with the New keyword much as you initialize a reference variable. The following code allocates an SPerson structure variable using the two-parameter constructor:

Dim artist As New SPerson("Sergio", "Aragones")

You can also use structure constructors later to reinitialize a variable or set its values, as shown ...

Get Visual Basic 2012 Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.