5

This maybe a silly question, why there is no Length property for queue or list, but only Count? And similarly why there is Length property for array?

Thanks

spspli
  • 3,128
  • 11
  • 48
  • 75

1 Answers1

1

Arrays are fixed Size, they are always initialized by defining the size upfront.

.Length makes sense here because it fixed, there are no operations involved to know this (think no counting)

Versus .Count on the other hand implies that the size is dynamic and there is an operation involved (counting) to know the size

Why there is no .Length property for a Collection or List?

That is indeed a good question, part of the answer is the different above, but it is also influenced by the framework design itself

In the framework design, a Collection is Enumerable, and any Enumerable has an Enumerator

The count of Lists or Collections works by getting that Enumerator for the Collection, and then iterating through the items while incrementing a counter

Here is the implementation of .Count() method found in System.Linq extensions

public static int Count<TSource>(this IEnumerable<TSource> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    ICollection<TSource> is2 = source as ICollection<TSource>;
    if (is2 != null)
    {
        return is2.Count;
    }
    int num = 0;
    using (IEnumerator<TSource> enumerator = source.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            num++;
        }
    }
    return num;
}
Bishoy
  • 3,915
  • 29
  • 37
  • 1
    A grain of salt. There is the method `Count()` and the property `Count`. The method implies calculation and it may be the case that the collection is iterated in order to obtain its count (albeit sometimes this might not even be the case). However, `ICollection.Count` doesn't usually involves a calculation. The method provided by Linq was in order to simplify working with enumerables (which have a important difference to lists) which do not provide (by design) a count/length property. – Bruno Brant Feb 07 '19 at 17:34