O'Reilly logo

Microsoft® Visual Basic® .NET Programmer's Cookbook by Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required