markzzz
markzzz

Reputation: 47995

Why I can't access to the Count property after a .ToList()

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

Answers (2)

Ufuk Hacıoğulları
Ufuk Hacıoğulları

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

Joachim VR
Joachim VR

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

Related Questions