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 the key differences are?
I might be wrong, but I always use the Count property in any conditional statements because I’m assuming the Count() method performs some sort of query against the collection, where as Count must have already been assigned prior to me ‘getting.’ But that’s a guess – I don’t know if performance will be affected if I’m wrong.
EDIT: Out of curiosity then, will Count() throw an exception if the collection is null? Because I’m pretty sure the Count property simply returns 0.
Decompiling the source for the
Count()extension method reveals that it tests whether the object is anICollection(generic or otherwise) and if so simply returns the underlyingCountproperty:So, if your code accesses
Countinstead of callingCount(), you can bypass the type checking – a theoretical performance benefit but I doubt it would be a noticeable one!