static void Main(string[] args)
{
var vs = new List<Person> { new Person(1) };
vs[0].IncrementAge();
Console.WriteLine(vs[0].Age); // output: 1
}
struct Person
{
public int Age { get; set; }
public Person(int age) : this()
{
Age = age;
}
public int IncrementAge()
{
Age++;
return Age;
}
}
I understand why we get a result like it. The list indexer returns a copy of the element. That is okay.
My question is that why we don't get the same result in the following code? because I changed the value of a copy of an element:
static void Main(string[] args)
{
var vs = new List<int> { 1 };
vs[0] = 2;
Console.WriteLine(vs[0]); // output: 2, **why not 1?**
}
Why does overwriting the entire value of a copy of an element affect list? I want to know how this code works in the background.