0

My code

list1.AddRange(list2);
foreach (var item in list2)
{
    item.Value--;
}

when I change the value in list2, the values added to list1 before are also changed

how can the value in list1 not be changed?

Anh Đinh
  • 13
  • 2
  • 3
    Don't add the same item to both lists. Add a copy/clone to the 2nd list. – Magnus Nov 10 '22 at 07:42
  • It depends. Maybe records can help you here as they behave like value types and are usually copied automatically. – Klamsi Nov 10 '22 at 07:48
  • 3
    You might also want to read: [What is the difference between a reference type and value type in c#](https://stackoverflow.com/questions/5057267/what-is-the-difference-between-a-reference-type-and-value-type-in-c) – Magnus Nov 10 '22 at 07:55
  • @Magnus how can i make a copy of list2, i tried using `CopyTo` but it doesn't seem to work – Anh Đinh Nov 10 '22 at 08:02
  • Not a copy of the list, a copy of the items you add. – Klamsi Nov 10 '22 at 08:21

0 Answers0