First of all, let's see how to copy a list in the simplest way with two simple List<int>.
- List<int> listA = new List<int>() { 10, 20 };
- List<int> listB = new List<int>() { };
- listB = listA.Select(x => { x = 0; return x; }).ToList();
It works without any problem and the result is given below.
ListA:
[0]: 10
[1]: 20
ListB:
[0]:0
[1]:0
Now, let's see what happens, if we try it with a reference type.
- List<string> listA = new List<string>() { "Peter", "Eve" };
- List<string> listB = new List<string>() { };
- listB = listA.Select(x => { x = "Doe"; return x; }).ToList();
ListA:
[0]: Peter
[1]: Eve
ListB:
[0]:Doe
[1]:Doe
Thus, basically copying a list doesn't depend solely on the value or the reference types, since it worked the same way with both the types.
Let's see what happens, if we try it with a complex type.
Let's see what happens, if we try it with a complex type.
Let's create a simple class, as shown below.
- class Person
- {
- public string Firstname { get; set; }
- public string Lastname { get; set; }
- }
Join the conversation! Your thoughts help the community grow.