0

Why does string EndsWith and StartsWith equals true with string.Empty in c# and explain the reason behind this, why it is this way.

string str = "string";
Console.WriteLine(str.EndsWith(string.Empty));   // returns true... why?
Console.WriteLine(str.StartsWith(string.Empty)); // returns true... why?     
Joris Brauns
  • 263
  • 1
  • 3
  • 17

2 Answers2

5

The empty string is a substring of every string and also occurs in every possible position – that includes at the start and the end.

Picture it this way: Each character in the needle has to occur in the same sequence at the start or end of the string. And the universal quantifier (∀) over an empty set is always true.

Joey
  • 344,408
  • 85
  • 689
  • 683
3

Why shouldn't it?

string.Empty + "string" + string.Empty = "string"
Ofir Winegarten
  • 9,215
  • 2
  • 21
  • 27