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
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
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 aCollection
orList
?
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;
}