A LINQ riddle

OK, this is inexcusably nerdy, but…

Are these two LINQ extension calls opposite?

bool allNumbersAreEven = numbers.All(x => x % 2 == 0);
bool noNumberIsEven = !numbers.Any(x => x % 2 == 0);

What do you think? It seems like a yes, doesn’t it?

The above two lines of code are logically similar to:

All fribbles are wibbles.
No fribble is a wibble.

Can both statements above possibly be true? In my personal opinion, no. But it does admittedly depend on your definition of “All.” Suppose there is no such thing as a fribble? Then certainly the second statement, “No fribble is a wibble,” must be true—no fribble is a wibble because no fribble is anything. But what about the first? “All fribbles are wibbles”? Seems kind of odd, doesn’t it?

I would argue that to speak of “All” of a nonexistent entity is pretty meaningless. And so I would expect the following to output False:

var numbers = new int[0]; // Empty set
Console.WriteLine(numbers.All(x => x % 2 == 0));

But: it outputs True. Very strange, if you ask me!

So the designers of the LINQ extension methods All and Any apparently felt that a statement about something that doesn’t exist is by default true. So I guess all fribbles really are wibbles… and all pluborgs are klugorgs… and all morbablobs are snorpaklods.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: