Getting the Number of Items in an IEnumerable

int GetCount(IEnumerable enumerable) {
  int count = 0;
  foreach (object o in enumerable)
  return count;

It’s that simple, right? Well, no, it isn’t. What you have to realize is that in contrast to ICollection, IList or IBindingList, IEnumerable is not an interface that’s by definition used with some kind of list or collection. IEnumerable (or rather IEnumerator, to which IEnumerable gives you access) is an iteration interface, a small but potentially important difference. The members of IEnumerable are really boring: just one method called GetEnumerator. That method returns IEnumerator and that one has exactly three members: Current (returns the element at the current position), Reset (sets the current position to the start of the iteration (really even before the start)) and MoveNext (move to the next item).

It’s clear, really, that these methods can theoretically return any number of items – they are not necessarily meant to have a pre-defined end. Consider that the interface may be returning data from some kind of live data source, which will probably go on delivering data forever. So, it is simple after all: if you want a count, you have to make assumptions about the nature of the IEnumerable implementation you use. As we all like compiler checked code, you shouldn’t make assumptions, because those are by definition not proveable – or they would be deductions.

If you think you know something about the type that’s being passed in, apart from that it implements IEnumerable, use that information to modify your method definition, e.g. by using ICollection instead of IEnumerable. If you find that you need a count, you know you can get a count, but you still think there’s no other way than using IEnumerable, then your design is flawed. Go fix it now before it gets worse.

Sorry, this blog does not support comments.

I used various blog hosting services since this blog was established in 2005, but unfortunately they turned out to be unreliable in the long term and comment threads were lost in unavoidable transitions. At this time I don't want to enable third-party services for comments since it has become obvious in recent years that these providers invariably monetize information about their visitors and users.

Please use the links in the page footer to get in touch with me. I'm available for conversations on Keybase, Matrix, Mastodon or Twitter, as well as via email.