title: Assign value to iteration variable in C#?
body: <p>I have the following code in C# utilizing <code>foreach</code>. In one loop I am modifying a <code>List&lt;T&gt;</code>, and in another, a <code>string</code> array. </p>
  
  <p>We can't directly assign a value or null to the iteration variable, but we can modify its properties, and the modifications are reflected in the <code>List</code> finally. </p>
  
  <p>So this basically means the iteration variable is a reference to the element in the list, so why we can't assign a value to it directly?</p>
  
  <pre><code>class Program
  {
      public static void Main(string[] args)
      {
          List&lt;Student&gt; lstStudents = Student.GetStudents();
  
          foreach (Student st in lstStudents)
          {
              // st is modified and the modification shows in the lstStudents
              st.RollNo = st.RollNo + 1;
  
              // not allowed
              st = null;
          }
  
          string[] names = new string[] { "me", "you", "us" };
  
          foreach (string str in names)
          {
              // modifying str is not allowed
              str = str + "abc";
          }
      }
  }
  </code></pre>
  
  <p>The student class:</p>
  
  <pre><code>class Student
  {
      public int RollNo { get; set; }
      public string Name { get; set; }
  
      public static List&lt;Student&gt; GetStudents()
      {
          List&lt;Student&gt; lstStudents = new List&lt;Student&gt;();
  
          lstStudents.Add(new Student() { RollNo = 1, Name = "Me" });
          lstStudents.Add(new Student() { RollNo = 2, Name = "You" });
          lstStudents.Add(new Student() { RollNo = 3, Name = "Us" });
  
          return lstStudents;
      }
  }
  </code></pre>