Changing objects value in foreach loop?

user2553512 picture user2553512 · Jul 16, 2013 · Viewed 96.6k times · Source

In one place i am using the list of string in that case the i am able to change the value of the string as code given below,

foreach(string item in itemlist.ToList())
{
    item = someValue; //I am able to do this 
}

But for object of class i am not able to alter the members value of the object the code is as below,

public class StudentDTO
{
    string name;
    int rollNo;
}

studentDTOList=GetDataFromDatabase();

foreach(StudentDTO student in studentDTOList.ToList())
{
      student = ChangeName(student); //Not working 
}

private StudentDTO ChangeName(StudentDTO studentDTO)
{
     studentDTO.name = SomeName;
     return studentDTO;
}

Error is : Can not assign because it's iteration variable

Answer

Olivier Jacot-Descombes picture Olivier Jacot-Descombes · Jul 16, 2013

You cannot change the iteration variable of a foreach-loop, but you can change members of the iteration variable. Therefore change the ChangeName method to

private void ChangeName(StudentDTO studentDTO)
{
    studentDTO.name = SomeName;
}

Note that studentDTO is a reference type. Therefore there is no need to return the changed student. What the ChangeName method gets, is not a copy of the student but a reference to the unique student object. The iteration variable and the studentDTOList both reference the same student object as does the studentDTO parameter of the method.

And change the loop to

foreach(StudentDTO student in studentDTOList)
{
    ChangeName(student);
}

However, methods like ChangeName are unusual. The way to go is to encapsulate the field in a property

private string name;
public string Name
{
    get { return name; }
    set { name = value; }
}

You can then change the loop to

foreach(StudentDTO student in studentDTOList)
{
    student.Name = SomeName;
}

EDIT

In a comment you say that you have to change many fields. In that case it would be okay to have a method UpdateStudent that would do all the changes; however I still would keep the properties.

If there is no additional logic in the properties besides passing through a value, you can replace them by the handy auto-implemented properties.

public string Name { get; set; }

In that case you would have to drop the field name.