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. Visual Basic 2005 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, as shown in Example 18-4. Example 18-4. Copy constructorPublic Sub New(ByVal existingObject As Time) year = existingObject.year month = existingObject.month dayOfMonth = existingObject.dayOfMonth 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(timeObject) 18.9.1. The Me KeywordThe keyword Me refers to the current instance of an object. The Me reference is a hidden reference to every non-Shared method of a class (Shared methods are discussed later). Each method can refer to the other methods and variables of that object by way of the Me reference. The Me reference may be used to distinguish instance members that have the same name as parameters, as in the following: Public Sub SomeMethod(ByVal hour As Integer) Me.hour = hour End Sub In this example, SomeMethod takes a parameter (hour) with the same name as a member variable of the class. The Me reference is used to resolve the ambiguity. While Me.hour refers to the member variable, hour refers to the parameter.
Another use of the Me reference is to pass the current object as a parameter to another method. For example: Public Sub myMethod( ) Dim someObject As New SomeType( ) someObject.SomeMethod(Me) End Sub In this code snippet, you call a method on an object, passing in the Me reference. This allows the method you're calling access to the methods and properties of the current object. You can also use the Me reference to make the copy constructor more explicit: Public Sub New(ByVal that As Time) Me.year = that.year Me.month = that.month Me.dayOfMonth = that.dayOfMonth Me.hour = that.hour Me.minute = that.minute Me.second = that.second End Sub In this snippet, Me refers to the current object (the object whose constructor is running) and that refers to the object passed in. |