C # - list member needs deep copy?

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

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

+5
source share
3 answers

It completely depends on how you plan to use the copy.

If you make a shallow copy, for example

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 are making 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}

, , .

+9

List<int> originalList = new List{1, 2} :
List<int> newList = new List<int>();
foreach(int i in originalList)
newList.Add(i);

.

, , , - , . , .

+2

, .

, , . ? , ints, , , .... , , , .

+1

All Articles