When utilizing the ToList() method, one may wonder about its impact on the existing list of objects. This article delves into the behavior of ToList() and its implications for object immutability.
Consider the following code:
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; }
When ToList() is invoked, it creates a new list that contains references to the original objects. To understand this, it's important to recognize that the original list (objs) holds references to instances of the MyObject class. ToList() doesn't copy the objects themselves; instead, it replicates the collection of references. This means that any modifications made to objects within the new list will be reflected in the original list because they both reference the same underlying objects.
In the provided code, changing the SimpleInt property of an object in the objectList list will also modify the corresponding object in the objs list. This occurs because both lists point to the same instances of MyObject. As a result, the method ChangeToList will return 5, indicating the updated SimpleInt property value.
However, if the MyObject class were declared as a struct instead of a class, ToList() would create a new list containing copies of the objects in the original list. In this scenario, modifying an object in the new list would not affect the original list, preserving its immutability.
The above is the detailed content of Does `ToList()` Create a Deep Copy or Just a Shallow Copy of a List?. For more information, please follow other related articles on the PHP Chinese website!