Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ToList does not shortcut if input is already a list

Tags:

c#

linq

The ToReadOnlyCollection extension method is implemented with a shortcut statement to return the input directly if it is already an instance of ReadOnlyCollection. The ToList extension method isnt.

Purely out of curiosity, is there a particular reason for this, or just something that happens not to have been implemented. I can see why guaranteeing that ToList will always return a new instance might be useful, but id be interested to know if theres any other reason.

like image 944
richzilla Avatar asked Dec 09 '22 04:12

richzilla


1 Answers

A read only collection can't be modified so it is perfectly acceptable to return the same instance as a result of .ToReadOnlyCollection().

If the result of a .ToList() operation sometimes returned a new list and sometimes didn't you wouldn't know if you're modifying the source list when changing the output list. So, for this reason, .ToList() always returns a new instance.

like image 106
Enigmativity Avatar answered Dec 10 '22 19:12

Enigmativity