Reputation: 47995
I have this code :
var numbers = new []{ 1,2,3 };
IEnumerable<int> evenNumbers = numbers.Where(i=> i % 2 == 0);
now I turn this "collection" into a List :
evenNumbers = evenNumbers.ToList();
why now I can do only evenNumbers.Count()
and not evenNumbers.Count
?
With :
IList<int> evenNumbers = numbers.Where(i=> i % 2 == 0).ToList();
I can. Wont' evenNumbers = evenNumbers.ToList();
materialize IEnumerable into a List?
Upvotes: 1
Views: 120
Reputation: 38488
evenNumbers
variable is still IEnumerable<int>
after the assignment. You should create a new variable type of IList<int>
or List<int>
to use Count
property since it's defined in the IList<T>
interface. That's what you do in your second assignment.
Upvotes: 1
Reputation: 2340
To your compiler, evenNumbers is still of the type IEnumerable. Your compiler has no idea that it's actually a List. The type of your variable, 'evenNumbers' doesn't change if you assign an object of a derived type to it.
Upvotes: 1