Thursday, May 4, 2017

Doing a .ToList() off of a list in C#, yes, makes a new reference type with a new pointer.

That said, the objects in the collection, should they be reference types, are going to be the same objects with the same pointers in the two lists. Anyways, beyond that caveat, note that this...

List<Whatever> yinlist = yangList.ToList();

 
 

...is basically the same thing as this...

List<Whatever> yinlist = new List<Whatever>();
foreach (Whatever yang in yangList)
{
   yinlist.Add(yang);
}

 
 

...and that ReSharper will even suggest changing the later to the former. Neither is the same though as:

List<Whatever> yinlist = yangList;

 
 

The last blob of code above will make a separate variable with a pointer to the same spot on the heap as yangList. (a separate variable without a separate pointer)

No comments:

Post a Comment