The property Count from ICollection is still ar

2019-09-21 05:39发布

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?

2条回答
2楼-- · 2019-09-21 06:17

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.

查看更多
不美不萌又怎样
3楼-- · 2019-09-21 06:29

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 implements ICollection<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.)

查看更多
登录 后发表回答