Alex Rivera | Logout

OOC: What is the difference between ToList() and casting to List<T> in .NET?

Asked 2010-01-21T05:23:08.113
13

OOC: Out Of Curiosity

So, as a little exercise and for the sake of learning, I decided to check if I was able to implement a very basic recursive function that would return a List<int>, but with the following restrictions:

1- The result should be returned by the function itself (as opposed to passed as an argument to a void function).

2 - No local "named" variables declared in the function's body.

I came up with the solution below (BTW: can this be improved in any way?)

While doing this, I learnt that ToList() is not the same thing as casting to List<T> (see example below) - Anyone out there who can explain what happens under the hood and what the difference between the two is?

Thanks!

PS - I'm using version 4.0 (in case it matters).

EDIT: the runtime error is Unable to cast object of type '<ConcatIterator>d__71'1[System.Int32]' to type 'System.Collections.Generic.List'1[System.Int32]'

public static List<int> SomeIntegers(int min, int max)
{
    //assume max >= min for simplicity  
    if (min == max)
        return new List<int>() { min };

    // runtime error 
    //return (List<int>)(SomeIntegers(min, max - 1).Concat(new List<int>() { max }));   

    //works
    return (SomeIntegers(min, max - 1).Concat(new List<int>() { max })).ToList(); 
}
Edit
Report

1 Answer

7
  • Casting only works if you actually have a List<T>, something derived from List<T>, or something with a valid type conversion to List<T>, otherwise it fails with an InvalidCastException. ToList() works on any IEnumerable.
  • ToList() always creates a new copy of the list even if you already have a list. Casting something to List<T> typically does not produce a copy of the list - it just gives you a new compile-time type for the same object.
answered 2010-01-21T05:27:40.043

Your Answer