6

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

Code:

var line = "name:";
Console.Write(line.Split(new char[] { ':' })[1].All(char.IsDigit)); 

How it is possible? it should not return false? after: is an empty string.

Community
  • 1
  • 1
The Mask
  • 17,007
  • 37
  • 111
  • 185

3 Answers3

15

Enumerable.All

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

Paul Tyng
  • 7,924
  • 1
  • 33
  • 57
8

It's a vacuously true expression.

All of the characters are digits because you can't find a counter-example. This code:

return s.All(char.IsDigit);

is roughly equivalent to this loop:

foreach (char c in s)
{
    if (!char.IsDigit(c)) { return false; }
}
return true;

In this rewritten version it should be clear that if there are no characters in the string then the loop body will never be entered and so the result is true.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
6

This is because of two reasons:

  1. As mentioned in your phantom edit update, your indexing condition grabs the second entry in the array returned by Split (C# counts starting at 0)

    var parts = line.Split(new char[] { ':' });
    // parts[0] == "name";
    // parts[1] == "";
    
  2. Enumerable.All<TSource>(...) returns true if the input sequence is empty

    Return Value

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

user7116
  • 63,008
  • 17
  • 141
  • 172