Previous section   Next section

7.3 Creating Structures Without New

Because loc1 is a structure (not a class), it is created on the stack. Thus, in Example 7-1, when the New keyword is called:

Dim loc1 As New Location(200, 300)

the resulting Location object is created on the stack.

The New keyword calls the Location constructor. However, unlike with a class, it is possible to create a structure without using New at all. This is consistent with how built-in type variables (such as Integer) are defined and is illustrated in Example 7-2.

Creating structures without the keyword New brings little advantage and can create programs that are harder to understand, more error prone, and more difficult to maintain! Proceed at your own risk.

Example 7-2. Creating a structure without New
Option Strict On
Imports System
Namespace StructureDemonstration

    ' declare a structure named Location
    Public Structure Location
        ' the Structure has private data
        Private myXVal As Integer
        Private myYVal As Integer

        Public Sub New( _
           ByVal xCoordinate As Integer, ByVal yCoordinate As Integer)
            myXVal = xCoordinate
            myYVal = yCoordinate
        End Sub 'New

        ' property

        Public Property XVal( ) As Integer
            Get
                Return myXVal
            End Get
            Set(ByVal Value As Integer)
                myXVal = Value
            End Set
        End Property

        Public Property YVal( ) As Integer
            Get
                Return myYVal
            End Get
            Set(ByVal Value As Integer)
                myYVal = Value
            End Set
        End Property

        ' display the structure as a String
        Public Overrides Function ToString( ) As String
            Return String.Format("{0}, {1}", XVal, YVal)
        End Function 'ToString
    End Structure 'Location

    Class Tester
        Public Sub Run( )
            ' create an instance of the structure
            Dim loc1 As Location  ' no call to the constructor
            loc1.XVal = 75
            loc1.YVal = 225

            ' display the values in the structure
            Console.WriteLine("Loc1 location: {0}", loc1)
        End Sub 'Run

        Shared Sub Main( )
            Dim t As New Tester( )
            t.Run( )
        End Sub 'Main

    End Class 'Tester
End Namespace 'StructureDemonstration

In Example 7-2, you initialize the local variables directly, before passing the object to WriteLine( ):

loc1.XVal = 75
loc1.YVal = 225

If you were to comment out one of the assignments and recompile:

Public Sub Run( )
    Dim loc1 As Location  ' no call to the constructor
    loc1.XVal = 75
    ' loc1.YVal = 225

    ' display the values in the Structure
    Console.WriteLine("Loc1 location: {0}", loc1)
End Sub 'Run

the unassigned value (YVal) would be initialized to its default value (in this case, 0):

loc1.XVal = 75
loc1.YVal = 0

  Previous section   Next section
Top