In Visual Basic, it is often necessary to create a copy of an object to modify data in a new way without affecting the original structure. The challenge is to differentiate between shallow and deep copying, especially if the objects contain nested reference types.
Background:
Shallow copying copies only the values of primitive properties and references to nested objects, while deep copying creates new instances of all nested objects. The distinction is crucial when working with complex data, for example, if an object contains collections or other objects.
Problem:
If you copy an object by reference or use the standard MemberwiseClone method, changing the nested objects will also change the original structure along with the copy — this is dangerous for business logic and can lead to elusive bugs.
Solution:
There is no straightforward built-in deep copying in VB.NET, so it should be implemented manually or through serialization. Typically, a custom DeepCopy method is implemented, creating new instances of all nested objects.
Example code for shallow and deep copying:
Class Person Public Name As String Public Address As Address ' Shallow copy Public Function ShallowCopy() As Person Return CType(Me.MemberwiseClone(), Person) End Function ' Deep copy Public Function DeepCopy() As Person Dim copy As Person = CType(Me.MemberwiseClone(), Person) copy.Address = New Address() With {.City = Me.Address.City} Return copy End Function End Class Class Address Public City As String End Class
Key features:
What does the = operator return when copying an object class in Visual Basic?
Answer: The = operator for reference types assigns a reference rather than copying values. Therefore, both variables will point to the same object.
Dim a As New Person() Dim b As Person = a ' Now a and b are references to the same object
Can MemberwiseClone be used for deep copying?
Answer: No. The MemberwiseClone method only implements shallow copying — all nested reference types are copied by reference.
Why is serialization not always a universal method for deep copying?
Answer: Serialization works only with serializable objects and may not support properties with the Object type or those not marked as Serializable. Additionally, serialization is slower than standard copying.
A client copies an order object using the = operator to create a new order, unaware that the nested item list remains the same for both objects.
Pros: Fast, simple
Cons: Changes in one order affect the other — critical errors in inventory management.
A DeepCopy method is implemented to copy the order along with all nested items and the shipping address.
Pros: Reliable data separation, correct business logic
Cons: Need to carefully monitor the object's structure, more code to maintain