Search code examples
c#linq

ToList() - does it create a new list?


Let's say I have a class

public class MyObject
{
    public int SimpleInt { get; set; }
}

And I have a List<MyObject>, and I ToList() it and then change one of the SimpleInt, will my change be propagated back to the original list. In other words, what would be the output of the following method and why?

public void RunChangeList()
{
    var objs = new List<MyObject>(){ new MyObject() { SimpleInt = 0 } };
    var whatInt = ChangeToList(objs);
}

public int ChangeToList(List<MyObject> objects)
{
    var objectList = objects.ToList();
    objectList[0].SimpleInt = 5;
    return objects[0].SimpleInt;
}

Solution

  • Yes, ToList will create a new list, but because in this case MyObject is a reference type then the new list will contain references to the same objects as the original list.

    Updating the SimpleInt property of an object referenced in the new list will also affect the equivalent object in the original list.

    (If MyObject was declared as a struct rather than a class then the new list would contain copies of the elements in the original list, and updating a property of an element in the new list would not affect the equivalent element in the original list.)