Ad space (banner)
#๏ธโƒฃC# Lessons
Lesson 40 / 68

Shallow Copy vs. Deep Copy

In this lesson you will learn the difference between a shallow and a deep copy in C#, so you can avoid bugs caused by unintentionally shared data. This is for anyone searching for "C# shallow copy deep copy".

Assigning a C# class instance to another variable actually copies a reference to the same object. That is the shallow-copy situation for classes, and changing one of them affects the other.

In the sample code, var shallow = original makes shallow point at the same Address instance as original. So setting shallow.City = "Osaka" also changes what original.City prints.

A common stumbling block for beginners is the bug where "I copied it, but the original changed too". Understanding the difference between reference types and value types is unavoidable knowledge for working correctly with memory in C#.

In real-world development, when you genuinely need an independent duplicate, you have to write the deep-copy logic yourself.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C# directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)