top of page

How to describe Deep Copy and Shallow Copy for a job interview

This is a "Gotcha" interview question because an interviewer may want to test your deep knowledge of how copying in C# and .NET works.

To start, the assignment or "=" operator does not actually make a copy. It only takes a new variable and references the memory location of the original value. If you change the original variable, the copy will also be changed because it is referencing the same place. This will result in some really strange bugs.

To make an genuine copy or clone, you need to perform a "Shallow Copy" by using the "MemberwiseClone()" method that is provided in .NET. However, this will only copy value types like integers, bools and floats. Although strings are reference types, they will "look copied" in a shallow copy because strings are immutable, so any changes to a string are placed in a new memory location when that string is created.

If you want to copy an object that also contains an object, you can perform a "Deep Copy." You will have to create custom code that creates new values and assigns them to a new cloned copy that is ultimately passed back. You can also use .NET's built in Serialization and Deserialization functions, but make sure you need everything in the object before taking the performance and memory hit associated with that operation.


Search By Tags
No tags yet.
Follow Us
  • Facebook Basic Square
  • Twitter Basic Square
  • Google+ Basic Square
bottom of page