Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

For example,

Is...

List<SomeType> newList = oldList;

...the same as...

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

(oldList is a list of SomeType as well)?

like image 973
Alexandru Avatar asked Sep 05 '13 18:09

Alexandru


2 Answers

There will be one List and multiple references to it. This applies for all reference types (classes).

Value types (structs), on the other hand, are copied when assigned.

like image 105
Theodoros Chatzigiannakis Avatar answered Oct 21 '22 04:10

Theodoros Chatzigiannakis


The assignment operator is not a cloning operator. In case of reference types, it copies values of references.

like image 43
Wiktor Zychla Avatar answered Oct 21 '22 05:10

Wiktor Zychla