Previous Context
To understand what I'm questioning, see first the question "Why does .Count work without parentheses?"
In that question is discussed, Why exists Count
(property) and Count()
(method) in classes that implements ICollection<T>
. that question was answered satisfactorily.
But below the answer in a comment, another question was raised by finoutlook
:
The question
The property Count
is still around (in later .Net versions to LINq technology) for backward compatibility?
Although It can be truth (is still around for backward compatibility), in my point of view, backward compatibility is not the reason for this property still exists.
When you have a class that implement
ICollection<T>
in most of cases will be short way to count the elements internally (in private or protected scope of the class).And also a collection must have knowledge of how many elements it has. As far as i am concerned, this is the main purpose of this property.
No, it's around so that a collection can return how many elements there are directly, without having to iterate over it.
Enumerable.Count()
has an optimization such that if the collection implementsICollection<T>
, it will use the property instead of iterating over the collection one element at a time, which is what you'd have to do otherwise.It feels like a clearly useful property to me. Even if the framework were created today with LINQ in mind, I'm sure there would still be something very similar. (Admittedly I can think of various changes I'd like to see to the collection interfaces, but that's a different matter.)