Search code examples
c#list

Why IList<T> does not contain a Length property?


I tried to do this:

int listAverage = NumberList.Sum()/NumberList.Length;

where NumberList is an IList. It throws an error:

'System.Collections.Generic.IList' does not contain a definition for 'Length' and no extension method 'Length' accepting a first argument of type 'System.Collections.Generic.IList' could be found (are you missing a using directive or an assembly reference?)

That gets me thinking, why does List<T> not have a Length property? I know you can use Count instead, but Length has an O(1) time complexity.


Solution

  • According to my experience, the convention in .NET seems to be that arrays and strings have the Length property, and higher level countable collections have Count property. The IList<T> has a Count property which is in general should be O(1), but depends on the exact implementation. For example the most used List<T> does it definitely at O(1).

    The generic Count() method is an extension for any IEnumerable<T> type, and that has technically O(n) complexity indeed, because the number of items may not be known before enumerating every element, or giving the number requires some custom processing (like for example a Linq to SQL query result expressed by an IQueryable<T> interface).