Shallow Copy and Deep Copy in C#When we assign one object variable to another in several programming languages, such as Java or C#, we copy a reference to the object's location in memory, not the object itself. So, both variables point to the same object instance in memory. It contrasts value-type variables like ints, bools, etc., which directly contain the actual value. For example: Here, g1 and g2 are reference variables that store references (memory addresses) pointing to the actual MyClass object in memory, say address 5000. When we assign g1 to g2 with =, we are copying the reference, so now both g1 and g2 pointers refer to the SAME MyClass instance at address 5000. Therefore, any changes made to the object via g1 or g2 will be visible when accessing the object through both because there is still only one actual object. It is different from copying a value type like an int, where g2 would store its independent copy of the value. So, in summary, the = assignment operator with reference types copies the reference, not the actual object, causing both references to point to the same instance. Value types directly contain values, so the assignment copies the value into the new variable. What is Shallow Copy?A shallow copy of an object does not make new copies of the nested objects-rather, it copies the reference to the nested objects. It means the copied object points to the same nested objects as the original object. In more detail:
Example:Let us take a C# program to show the Shallow copy concept. Output: Original: Person: Jane, Age: 25, Hobbies: Reading, Gaming, Traveling Copy: Person: John, Age: 30, Hobbies: Reading, Gaming, Traveling What is Deep Copy?A deep copy is an object copy that fully duplicates all levels of nested objects in the original object. It means instead of copying object references to the nested objects, it creates new instances of those nested objects. In more detail:
Example:Let us take a C# program to show the Deep copy concept. Output: Original: Person: Virat, Age: 25 Copy: Person: Virat, Age: 30 Next TopicType.FindMembers() Method in C# |