Title | Give a class a Clone method in Visual Basic .NET |
Description | This example shows how to give a class a Clone method in Visual Basic .NET. |
Keywords | class, clone, VB.NET |
Categories | VB.NET, Miscellany, Software Engineering |
|
|
Sometimes it's useful for a class to provide a method for making copies of one of its instances. The following code shows the Person class. Its Clone method makes a copy of its instance and casts the result into a Person object.
|
|
Public Class Person
Public FirstName As String
Public LastName As String
Public Function Clone() As Person
Return DirectCast(Me.MemberwiseClone(), Person)
End Function
End Class
|
|
The following code shows how the main program uses this class when you click the Clone button. The program makes a new Person object and initializes its FirstName and LastName fields. It then calls the object's Clone method to make a new Person object and displays the clone's fields.
|
|
' Make a Person.
Dim per1 As New Person
per1.FirstName = txtFirstName.Text
per1.LastName = txtLastName.Text
' Clone.
Dim per2 As Person = per1.Clone()
' Display the new person.
lblFirstName.Text = per2.FirstName
lblLastName.Text = per2.LastName
|
|
Note that MemberwiseClone only copies value fields not references. For example, if the Person class included a Manager field that was a reference to another Person object, MemberwiseClone would not copy it. In that case, you would need to change the Clone function to either make the clone's Manager field point to the same Person or make the clone's Manager field point to a new Person.
Note also that the .NET Framework defines an ICloneable interface that requires you to implement a Clone method. Unfortunately that version returns a generic Object so the calling code must use DirectCast to convert the result into the more specific type (Person in this example).
|
|
|
|