Why does Enumerable.All return true for an empty sequence?

Cui Pengfei 崔鹏飞 picture Cui Pengfei 崔鹏飞 · Oct 25, 2011 · Viewed 34.2k times · Source
var strs = new Collection<string>();
bool b = strs.All(str => str == "ABC");

The code creates an empty collection of string, then tries to determine if all the elements in the collection are "ABC". If you run it, b will be true.

But the collection does not even have any elements in it, let alone any elements that equal to "ABC".

Is this a bug, or is there a reasonable explanation?

Answer

Jon Skeet picture Jon Skeet · Oct 25, 2011

It's certainly not a bug. It's behaving exactly as documented:

true if every element of the source sequence passes the test in the specified predicate, or if the sequence is empty; otherwise, false.

Now you can argue about whether or not it should work that way (it seems fine to me; every element of the sequence conforms to the predicate) but the very first thing to check before you ask whether something is a bug, is the documentation. (It's the first thing to check as soon as a method behaves in a way other than what you expected.)