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;
}
}