In this post I am investigating the difference between Count property and Count() extension method of the .NET enumerable. Below code snippet sets the scene of what we trying to answer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
static void Main(string[] args) { IList<int> ages = ReadAges(); int ageCount = ages.Count; //Interface Property //OR int ageLinqCount = ages.Count(); //Linq extension IEnumerable<string> names = ReadNames(); var nameCount = names.Count(); //Linq extension; only option } private static IEnumerable<string> ReadNames() { //... } private static IList<int> ReadAges() { //... } |
As in the previous post will start by decompiling the System.Core 4.0.0.0 dll.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
//Count() extension method implementation public static int Count<TSource>(this IEnumerable<TSource> source) { if (source == null) { throw Error.ArgumentNull("source"); } ICollection<TSource> collection = source as ICollection<TSource>; if (collection != null) { return collection.Count; } ICollection collection2 = source as ICollection; if (collection2 != null) { return collection2.Count; } int num = 0; checked { using (IEnumerator<TSource> enumerator = source.GetEnumerator()) { while (enumerator.MoveNext()) { num++; } } return num; } } |
The Linq Count() extension method behaves differently based on the…