Why does this condition return true?

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

the code:

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

How is this possible? shouldn't it return false? after : is an empty string.

+6
source share
3 answers

Enumerable.All

true if each element of the original sequence passes the test to the specified predicate, or if the sequence is empty ; otherwise false.

+15
source

This expression is vacuously true .

All characters are numbers because you cannot find a counter example. This code:

 return s.All(char.IsDigit); 

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, the loop body will never be entered and the result will be true.

+8
source

There are two reasons for this:

  • As mentioned in your phantom edit update, your indexing condition captures the second record in the array returned by Split (C # number starts at 0)

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

    Return value

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

+6
source

Source: https://habr.com/ru/post/900460/


All Articles