Assign value to iteration variable in C#?

c#, foreach, iteration

Solution

The iteration variable in a `foreach` is not a "reference to the element in the list" - it is merely the value from `.Current {get;}` in an iterator implementation obtained via `GetEnumerator()` - most commonly via `IEnumerator[<T>]` but not always - indeed for a `List<T>` it is a `List<T>.Enumerator` value. In the general case, there is no "meaning" to assigning to the iterator variable. Consider:

IEnumerable<int> RandomSequence(int count) {
    var rand = new Random();
    while(count-->0) yield return rand.Next();
}

This will work identically from a `foreach` - what would it mean to assign to it?

Thus, `foreach` offers no facility to assign to the iterator variable.

Problem

I have the following code in C# utilizing `foreach`. In one loop I am modifying a `List<T>`, and in another, a `string` array. 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 `List` finally. 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? ``` class Program { public static void Main(string[] args) { List<Student> 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"; } } } ``` The student class: ``` class Student { public int RollNo { get; set; } public string Name { get; set; } public static List<Student> GetStudents() { List<Student> lstStudents = new List<Student>(); 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; } } ```

Original source