Home >Backend Development >C++ >Does C#'s ToList() Create a Deep Copy or a Shallow Copy of the List's Elements?
ToList(): Does It Create a New List?
In C#, ToList() is a method that creates a new list with copies of the elements from the existing list. In the case of reference types like classes, the copies contain references to the same objects as the originals.
Consider the following code:
public class MyObject { public int SimpleInt { get; set; } } ... 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; }
In this code, the ChangeToList method takes a list of MyObject objects and converts it to a new list using ToList(). It then modifies the SimpleInt property of the first object in the new list.
The key point to note here is that MyObject is a reference type. Therefore, the ToList() operation creates a new list, but the elements in the new list are references to the same objects in the original list. Consequently, when the SimpleInt property of the object referenced in the new list is modified, the change is also reflected in the corresponding object in the original list. This is why the output of the RunChangeList() method would be 5, as the modification made in the new list is propagated to the original list.
The above is the detailed content of Does C#'s ToList() Create a Deep Copy or a Shallow Copy of the List's Elements?. For more information, please follow other related articles on the PHP Chinese website!