Create Shallow and Deep Copies of a Collection or Array


You need to copy a collection.


To create a shallow copy, use the Clone method. To create a deep copy, iterate over the collection, and copy each item.


All collection types provide a Clone method that makes it easy to quickly copy the entire collection.

' Create an ArrayList and add some items.
Dim ListA As New ArrayList()

' Create a duplicate ArrayList.
Dim ListB As ArrayList()
ListB = CType(ListA.Clone(), ArrayList)

This is known as a shallow copy, and it works fine for value types (or reference types that behave like value types, such as String). However, this method isn’t always appropriate when used with ordinary ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.