Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - List member needs deep copy?

Tags:

c#

I have class with a List<int> member. If I want to clone an instance of this class, do I need a deep copy or the MemberwiseClone() shallow copy is enough?

We need a deep copy if at least one member is a reference to an object, right? Does that mean having List, DateTime, String, MyClass, ..., will need a deep copy?

like image 517
5YrsLaterDBA Avatar asked Feb 22 '10 21:02

5YrsLaterDBA


1 Answers

This entirely depends on how you plan to use the copy.

If you do a shallow copy like

List<int> x = new List<int>() { 1, 2, 3, 4, 5 };
List<int> y = x;
y[2] = 4;

Then x will contain {1, 2, 4, 4, 5 }

If you do a deep copy of the list:

List<int> x = new List<int> { 1, 2, 3, 4, 5 };
List<int> y = new List<int>(x);
y[2] = 4;

Then x will contain { 1, 2, 3, 4, 5 } and y will contain { 1, 2, 4, 4, 5 }

How you plan on using the copy really determines whether you use shallow or deep copies.

like image 186
Robert Davis Avatar answered Oct 07 '22 14:10

Robert Davis