Here is the problem:
I have this class Person
:
class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Position { get; set; }
public int Age { get; set; }
}
I initialized this object named workersA
as the source object:
List<Person> workersA = new List<Person>()
{
new Person { Id = 1, Name = "Emp1", Age = 27 },
new Person { Id = 2, Name = "Emp2", Age = 18 },
new Person { Id = 3, Name = "Emp3", Age = 23 },
};
I declare the other two instances as this:
List<Person> workersB = new List<Person>();
List<Person> workersC = new List<Person>();
And fill it with different approach:
On workersB
stored from source using .ToList()
extension.
workersB = workersA.ToList();
And on workersC
stored from source using foreach
statement.
foreach (var w in workersA.ToList())
{
workersC.Add(w);
}
Now when i try to modify the Age
property of the source object.. here's the code:
foreach (var p in workersA.ToList())
{
p.Age--;
}
And output all the result using this code:
Console.WriteLine("Wokers A:");
foreach (var p in workersA.ToList())
{
Console.WriteLine("Id: {0} Name: {1}, Age: {2}", p.Id, p.Name, p.Age);
}
Console.WriteLine();
Console.WriteLine("Wokers B:");
foreach (var p in workersB.ToList())
{
Console.WriteLine("Id: {0} Name: {1}, Age: {2}", p.Id, p.Name, p.Age);
}
Console.WriteLine();
Console.WriteLine("Wokers B:");
foreach (var p in workersB.ToList())
{
Console.WriteLine("Id: {0} Name: {1}, Age: {2}", p.Id, p.Name, p.Age);
}
Here is what ive'd got:
Wokers A:
Id: 1 Name: Emp1, Age: 26
Id: 2 Name: Emp2, Age: 17
Id: 3 Name: Emp3, Age: 22
Wokers B:
Id: 1 Name: Emp1, Age: 26 // 27 - expectation
Id: 2 Name: Emp2, Age: 17 // 18 - expectation
Id: 3 Name: Emp3, Age: 22 // 22 - expectation
Wokers C:
Id: 1 Name: Emp1, Age: 26 // 27 - expectation
Id: 2 Name: Emp2, Age: 17 // 18 - expectation
Id: 3 Name: Emp3, Age: 22 // 22 - expectation
To address the question clearly
Why did i get the same output?