Search code examples
c#deep-copy

Copy elements from List<byte> to another List<byte> doing a deep copy


I'm developing a C# library with .NET Framework 4.7.

I have two List<byte> and I want to copy all the elements in one of them to the another one.

I want to reuse the list, so I don't want to create a new one when I have to copy the contents of one list to the other.

List<byte> list1 = new List<byte>() { 1, 2, 3, 4, 5, 6 };
List<byte> list2 = new List<byte>() { 7, 8, 9, 10, 11, 12 };

If I want to copy the content of list2 into list1, what do I have to do if I want to replace the content of list1 with the content of list2?

I want to copy the values, not to copy a reference to the values in list2. If I modify a value in list2 I don't want that modification in list1.

I haven't found any method that does a deep copy in List<T>. The only I think I can use is AddRange but I haven't found any reference about if this method does a deep or swallow copy.

What do I have to do if I want to replace the content of list1 with the content of list2 doing a deep copy?


Solution

  • byte is a value-type. So if you copy them, they are independent from the orignial value. Here are no references involved. And the term "deep-copy" doesn't make any sense if the lists contain only byte values.

    So yes, to copy the elements of list2 into list1 you can simply do

    list1.AddRange(list2);
    

    You might want to list1.Clear() before if you don't want to keep the previous content.