Copy Constructors

A copy constructor creates a new object by copying variables from an existing object of the same type. For example, you might want to pass a Time object to a Time constructor so that the new Time object has the same values as the old one.

VB.NET does not provide a copy constructor, so if you want one you must provide it yourself. Such a constructor copies the elements from the original object into the new one:

Public Sub New(ByVal existingObject As Time)
   year = existingObject.Year
   month = existingObject.Month
   date = existingObject.Date
   hour = existingObject.Hour
   minute = existingObject.Minute
   second = existingObject.Second
End Sub

A copy constructor is invoked by instantiating an object of type Time and passing it the name of the Time object to be copied:

Dim t2 As New Time(existingObject)

Here an existing Time object (existingObject) is passed as a parameter to the copy constructor that will create a new Time object ( ), as shown in Example 5-7.

Example 5-7. Copy constructor

Option Strict On Imports System Public Class Time ' Private variables Private year As Integer Private month As Integer Private date As Integer Private hour As Integer Private minute As Integer Private second As Integer = 30 ' Public methods Public Sub DisplayCurrentTime( ) Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}", _ month, date, year, hour, minute, second) End Sub 'DisplayCurrentTime Public Sub New( _ ByVal theYear As Integer, _ ByVal theMonth As Integer, _ ByVal theDate As Integer, _ ByVal ...

Get Programming Visual Basic .NET, Second Edition 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.