In .NET generic interface ICollection<T>
has Count
property itself. But it does not inherit any non-generic interface with a Count
property.
So, now if you want determine count of non-generic IEnumerable
, you have to check whether it is implementing ICollection
and if not, you have to use reflection to lookup whether it does implement generic ICollection<X>
, since you do not know the generic argument X
.
If ICollection<T>
cannot inherit from directly from ICollection
, why there is not another non-generic interface with Count
property only?
Is it just bad design choice?
UPDATE: To make the question more clear, I demonstrate the issue on my current implementation:
static int? FastCountOrZero(this IEnumerable items)
{
if (items == null)
return 0;
var collection = items as ICollection;
if (collection != null)
return collection.Count;
var source = items as IQueryable;
if (source != null)
return QueryableEx.Count(source);
// TODO process generic ICollection<> - I think it is not possible without using reflection
return items.Cast<object>().Count();
}