Home > Backend Development > C++ > Does `ToList()` Create a Deep Copy or Just a Shallow Copy of a List?

Does `ToList()` Create a Deep Copy or Just a Shallow Copy of a List?

Mary-Kate Olsen
Release: 2024-12-30 08:56:13
Original
979 people have browsed it

Does `ToList()` Create a Deep Copy or Just a Shallow Copy of a List?

Does ToList() Create a New List?

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template