Stellar Sword
Stellar Sword

Reputation: 6226

Modifying collections in foreach loop

Quick question:

public void ChangeObject(MyClass a){
  a.property = 55;
}

public void Test(){
  List<MyClass> obj_list = get_the_list();
  foreach( MyClass obj in obj_list )
  {
      ChangeObject(obj);
  }
}

Will this make all the values in obj_list have the property 55?

So somewhere else in my code I will call "if(obj_list[5].property == 55){ print("YES"); }" would be true after the loop.

Or do I need "ref"? Because it gives a lot of errors if you try to use ref (as you cannot modify iteration values).

Upvotes: 1

Views: 102

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500535

Will this make all the values in obj_list have the property 55?

Yes - assuming MyClass really is a class. Imagine that the list is really an addressbook - there's the address of a house on every page (element). The list doesn't contain the actual houses themselves - just a way of getting to them. Your foreach loop is like saying, "For each page in the book, go to the house whose address is listed on the page and write 55 on the front door."

Or do I need "ref"?

No. That would try to pass the variable by reference... and the iteration variable is readonly. See my article on parameter passing in C# for more details on this.

Upvotes: 3

Related Questions