Object Oriented Programming and C#: Shallow vs Deep Copying

The following will be a brief but important post illustrating the difference between reference and value types. In C#, value types are things like integers, floats, enumerations and doubles. A value type holds the data assigned to it in its own memory allocation whereas a reference type only holds an address which points to the actual data. A reference type is anything that is not an int, float or double, etc such as a dynamic array (list), static array, class objects, or strings. It is important to know the difference because when code such as the code below is executed, it can have some confusing effects.

shallow copy

The image above illustrates what is known as a “shallow copy”. Because instances of classes are not storing actual data but are used as pointers, when the object is copied to the second object, the memory address is copied instead of the data contained within “obj”. Therefore, any changes made to “obj2” will also affect “obj” because they point to the same data. The following image shows the difference between deep and shallow copies.

diff

To do a deep copy of an array, for instance, every element of that array must be copied to the new array. You can do that using the “Array.Copy(source array, copy array)” method. As shown in the image, this will create two references and two data instead of 2 references pointing to the same data. Shallow copying only copies a memory pointer.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s