Not really. For example, a
BillWoodruff wrote:If an IEnumerable "knew" its count ... is that a contradiction in terms ?
List<T> is also an
List<T> "knows" its count.
TryGetNonEnumeratedCount method simply attempts to cast the
IEnumerable<T> to a few "pre-counted" interfaces at run-time, and returns the
Count property from the first one that succeeds. You can see the source code on GitHub:
runtime/Count.cs at 57bfe474518ab5b7cfe6bf7424a79ce3af9d6657 · dotnet/runtime · GitHub[^]
IIListProvider<T>, and the non-generic
ICollection. That should cover most cases, although it notably doesn't try the
IReadOnlyCollection<T> introduced in .NET 4.5 - I can't find an official comment, but this SO thread[^] discusses that.
You can see the original proposal for this method on the runtime repository:
Non-enumerating Count Linq Method · Issue #27183 · dotnet/runtime · GitHub[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."