Create Shallow and Deep Copies of a Collection or Array

Problem

You need to copy a collection.

Solution

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

Discussion

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()
ListA.Add("blue")
ListA.Add("green")
ListA.Add("yellow")

' 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 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.