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.

1 Comment on Getting the number of items in an IEnumerable

  1. Thanks for the tip. I’ve been using IEnumerable incorrectly to an extent.


Leave a Comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s