views:

66

answers:

3

Hello,

I need to change a method that has one parameter that takes a serie of objects. I need to find the lowest Interface (in inheritance tree) that has the Count property. Until now I was using the IEnumerable but as this has not Count I need to change it to the wider interface possible so the method can work with the biggest number of types of series (collections, lists, arrays, etc).

Thanks in advance.

+6  A: 

ICollection adds the Count property.

As @Joren rightly points point, IEnumerable<T> has the extension method Count<T>() if you're happy making your collection generic. However, as @Joel Coehoorn has pointed out, it is inadvisable to use this as it forces an iteration of the sequence.

David Neale
That's the lowest at the Hierarchy tree?
SoMoS
The Count<T> method is an extension method on IEnumerable<T>, not a method on ICollection<T>. (ICollection<T> just has the Count property, which it inherits from ICollection.) Of course ICollection<T> inherits from IEnumerable<T>, so the extension method is valid on ICollection<T> instances. My point is that for the Count<T> method, IEnumerable<T> is more fundamental than ICollection<T>.
Joren
Ah, thanks @Joren. I'll amend the answer.
David Neale
Yes, ICollection is what adds the Count property. Other things that have the property will generally be implementing ICollection (IList, IDictionary etc.).
David Neale
Don't use IEnumerable's .Count extension. It forces an iteration of the sequence.
Joel Coehoorn
Thanks for pointing that out - answer amended.
David Neale
+4  A: 

ICollection adds the Count property.

Dean Harding
+3  A: 

System.Collections.ICollection, and also System.Collections.Generic.ICollection<T>. These two interfaces have no relation to eachother, but both inherit from IEnumerable, so they're at the same level.

IEnumerable obviously does not have a Count property (the count isn't necessarily predetermined).

Thorarin