0

I have some code that uses the Reverse extension method.

To make sure that it does not reverse the original list the original programmer used GetRange to create a new list.

dim a = New List(of Thing)
... fill in a
dim b = a.GetRange(0, a.count)
b.reverse()

Presumably GetRange guarantees to always create a new object. Does this apply to ToList as well?

Then I could write:

dim a = New List(of Thing)
... fill in a
dim b = a.ToList()
b.reverse()

The advantage then is that the type of a could be IEnumerable(of T) and it would still work.

I have tested this myself and it has always been true that b is a new object. The question is this:

Is it guaranteed that future implementations will behave the same or is this behaviour an accident of the implementation?

An obvious 'optimization' would be to return a reference to the original object if it were already a list, which would of course mean that the second version would reverse the original list.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Kevin Whitefoot
  • 414
  • 3
  • 15

3 Answers3

1

Based on this source, I would assume that it does but if the Query mentioned on the msdn article is empty then it would just return an empty list.

Seeing as you have not managed to disprove this you may need to conduct further research into this to find the true answer.

Nunners
  • 3,047
  • 13
  • 17
1

I don't see how this can be just an implementation detail.

IEnumerable<T> does not have to be a list at all. Just something that can be enumerated. So ToList() has no other choice than to traverse the whole enumerable and create a new list with all the results.

The only caveat I can think of is if they inside ToList specifically check if the input is of type List<T> and just return a reference to it.

But that will break so much existing code, that it will never happen.

Øyvind Bråthen
  • 59,338
  • 27
  • 124
  • 151
  • Some IEnumerable methods are definitely type checking. – argaz Sep 25 '13 at 10:37
  • @argaz - Indeed, like `Count()` for example. But doing that check for `ToList()` so that in some cases it creates a copy, and in other just a reference will never happen. As long as they can't create a reference for all enumerables (and they can't), they can't do it for any of them. – Øyvind Bråthen Sep 25 '13 at 11:01
  • Generally, it's understood `ToX()` will create a new reference and `AsX()` will return an existing reference, if one exists and create a new one, if no reference exists. (https://jira.codehaus.org/browse/GROOVY-1133) – nicodemus13 May 20 '14 at 14:57
1

From it's documentation:

Creates a List from an IEnumerable

which means a new instance.

You can be sure to create a new list using :

dim b =New List(Of T)(input) where input is an IEnumerable(Of T)

manji
  • 47,442
  • 5
  • 96
  • 103