Home >Backend Development >C++ >Does C#'s `ToList()` Create a New List of References or Copies of Elements?

Does C#'s `ToList()` Create a New List of References or Copies of Elements?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-02 19:05:39762browse

Does C#'s `ToList()` Create a New List of References or Copies of Elements?

Does ToList() Create a New List?

In C#, the ToList() method returns a new list that contains elements from the original collection. However, the question arises, does it create a new list of references or copies of the elements?

Consider the following example:

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

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;
}

In this scenario, ToList() creates a new list of references to the same objects as the original list. This is because MyObject is a reference type, meaning it stores the address of the object in memory.

When the SimpleInt property of an object referenced in the new list is changed, the change propagates back to the equivalent object in the original list. This is because both the new list and the original list reference the same object.

If MyObject were declared as a struct instead of a class, the ToList() method would create a new list with copies of the elements from the original list. In this case, changes made to elements in the new list would not affect the corresponding elements in the original list.

The above is the detailed content of Does C#'s `ToList()` Create a New List of References or Copies of Elements?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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