Advertisement
mjc65

Example 1-72. Changing items in a foreach

Jun 23rd, 2020
770
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.48 KB | None | 0 0
  1. class Person
  2. {
  3.     public string FirstName { get; set; }
  4.     public string LastName { get; set; }
  5. }
  6.  
  7. void CannotChangeForeachIterationVariable()
  8. {
  9.     var people = new List<Person>
  10.     {
  11.         new Person() { FirstName = "John", LastName = "Doe"},
  12.         new Person() { FirstName = "Jane", LastName = "Doe"},
  13.     };
  14.  
  15.     foreach (Person p in people)
  16.     {
  17.         p.LastName = "Changed"; // This is allowed
  18.         // p = new Person(); // This gives a compile error
  19.     }
  20. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement