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
Performance is only one reason to choose one or the other. Choosing .Count()
means that your code will be more generic. I've had occasions where I refactored some code that no longer produced a collection, but instead something more generic like an IEnumerable, but other code broke as a result because it depended on .Count
and I had to change it to .Count()
. If I made a point to use .Count()
everywhere, the code would likely be more reusable and maintainable. Usually opting to utilize the more generic interfaces if you can get away with it is your best bet. By more generic, I mean the simpler interface that is implemented by more types, and thus netting you greater compatibility between code.
I'm not saying .Count()
is better, I'm just saying there's other considerations that deal more with the reusability of the code you are writing.
If there is a Count
or Length
property, you should always prefer that to the Count()
method, which generally iterates the entire collection to count the number of elements within. Exceptions would be when the Count()
method is against a LINQ to SQL or LINQ to Entities source, for example, in which case it would perform a count query against the datasource. Even then, if there is a Count
property, you would want to prefer that, since it likely has less work to do.