How to: Define and Use a Structure in VB.NET

The structure is a programming entity similar to classes […]. The difference is that structures are value types while classes of objects are reference types.
A value type variable is declared and the space according to said data type is allocated at the execution time. Value type variable is destroyed when leaving the block where it has been defined.

A reference type variable involves a process of definition in two steps:

  • Variable declaration: requires use of a data type associated to the variable;
  • Variable instantiation: creates the object.

A reference type variable exists in two memory locations. Thus, when leaving the block that has been defined, the reference to the object is destroyed, but the object itself remains allocated in memory.
Structures are used for small objects and are defined between specifications Structure and End Structure.
The below application shows the process of defining the structure and use of a variable of structure type:

Module Module1
    Structure Persoana
        Dim CNP As String
        Dim Nume As String
        Dim Adresa As String
    End Structure

    Sub Main()
        Dim p As Persoana
        p = New Persoana
        p.CNP = "1801010433012"
        p.Nume = "Popescu Gigel"
        p.Adresa = "Bld. Victoriei nr. 13"

        MsgBox(p.Nume & " has the address " & p.Adresa)
    End Sub
End Module

Fields defined in the structure are accessed by the operator . which precedes the name of variable of structure type.
VB.NET application has the type Console Application, which requires procedure Main.