This morning I've struggled to understand the following and I am hoping someone has a good explanation of why this wont work. I made an example on LinqPad
that replicates my issue:
void Main()
{
var myPeople = new People();
myPeople.MyPeople.Add(new Person { Name = "Joe", Surname = "Doe" });
foreach (var person in myPeople.MyPeople)
{
//this is intermediate variable is still a reference to the iteration variable
var intermediate = person;
myPeople.ChangeName(ref intermediate);
//both names were changed, so why cant i just pass in 'person' directly since its still changing it.
intermediate.Name.Dump();
person.Name.Dump();
}
}
public class People
{
public People()
{
MyPeople = new List<Person>();
}
public List<Person> MyPeople { get; set; }
public void ChangeName(ref Person person)
{
person.Name = "Changed";
}
}
public class Person
{
public string Name { get; set; }
public string Surname { get; set; }
}
So this post explains the foreach
variable is a read only variable that is why you can't replace it with another- makes sense, but if i pass it into the method above ChangeName
with a ref
, compiler wont allow it CS1657. But if i remove the ref
on the ChangeName
method it will allow me to pass in the foreach variable, but technically its still a reference
without explicitly saying its a ref
right?
So why is this happening? Furthermore if I assign it to an intermediate variable above, then it will allow me to pass it in as a ref
even though its still a reference to the original, so technically pointing to the same memory location, meaning same object right?
So my question really is why the C# compiler wont let me pass in iteration variable to a method with a ref
Further clarity on question by Rafalon:
Why does the compiler not allow myPeople.ChangeName(ref person) but allows myPeople.ChangeName(ref intermediate) when the person
variable points to the same object as the intermediate
variable?