In C #, when I set a new list equal to another list, does it set the new list as a pointer to another list or actually creates a new list?

When I set a new list equal to another list, does it set the new list as a pointer to another list or does it actually create a new list?

For instance,

Is ...

List<SomeType> newList = oldList; 

... the same as ...

 List<SomeType> newList = new List<SomeType>(); newList.AddRange(oldList); 

(oldList is also a SomeType list)?

+4
source share
3 answers

There will be one List and several links to it. This applies to all reference types (classes).

On the other hand, value types (structures) are copied at assignment.

+8
source

The assignment operator is not a clone operator. In the case of reference types, it copies the values โ€‹โ€‹of the links.

+5
source

In type assignment:

 List<SomeType> newList = oldList; 

Both lists will be the same, adding or removing one item in the list will cause it to change in another list. They both use the same memory space next to the extra pointer.

 List<SomeType> newList = new List<SomeType>(); newList.AddRange(oldList); 

Will 2 share an independent list (both in memory). A change in one list will not affect the other.

Keep in mind if your "SomeType" is a complex type ... lets say "product". In BOTH CASE, the entire list will refer to your products, so the change in the product will be changed in another list.

To copy the list and the product necessary for cloning the product, and which can be a hoax, because cloning is recursive depending on the complexity of the type.

+2
source

Source: https://habr.com/ru/post/1500791/


All Articles