Working with a collection I have the two ways of getting the count of objects; Count
(the property) and Count()
(the method). Does anyone know what
Decompiling the source for the Count()
extension method reveals that it tests whether the object is an ICollection
(generic or otherwise) and if so simply returns the underlying Count
property:
So, if your code accesses Count
instead of calling Count()
, you can bypass the type checking - a theoretical performance benefit but I doubt it would be a noticeable one!
// System.Linq.Enumerable
public static int Count(this IEnumerable source)
{
checked
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
ICollection collection = source as ICollection;
if (collection != null)
{
return collection.Count;
}
ICollection collection2 = source as ICollection;
if (collection2 != null)
{
return collection2.Count;
}
int num = 0;
using (IEnumerator enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
num++;
}
}
return num;
}
}