9

I jumped into this accidentally and have no clue as to why this is happening

string sample = "Hello World";
if (sample.Contains(string.Empty))
{
    Console.WriteLine("This contains an empty part ? at position " + sample.IndexOf(string.Empty));
    Console.WriteLine(sample.LastIndexOf(string.Empty));
    Console.WriteLine(sample.Length);
}

Output

This contains an empty part ? at position 0

10

11

I am happy with the last part, but i have no idea why this is evaluated true. Even Indexof and LastIndexOf have separate values.

Could anyone help me out on why is this so?

EDIT

I believe this is a bit relevant to my question and would be also helpful to those who stumble upon this question.

See this SO link: Why does "abcd".StartsWith("") return true?

Cœur
  • 37,241
  • 25
  • 195
  • 267
V4Vendetta
  • 37,194
  • 9
  • 78
  • 82

3 Answers3

16

From msdn for IndexOf

If value is String.Empty, the return value is 0.

For LastIndexOf

If value is String.Empty, the return value is the last index position in this instance.

For Contains

true if the value parameter occurs within this string, or if value is the empty string ("");

SwDevMan81
  • 48,814
  • 22
  • 151
  • 184
4

Question: Does the string "Hello World" contain String.Empty?

Answer: Yes.

Every possible string contains String.Empty, so your test is correctly returning true.

If you are trying to test if your string is empty, then the following code is what you want

if (string.IsNullOrEmpty(sample)) 
{

}
RB.
  • 36,301
  • 12
  • 91
  • 131
1

This is documented in the String.Contains Method:

Return Value
Type: System.Boolean
true if the value parameter occurs within this string, or if value is the empty string (""); otherwise, false.

And in String.IndexOf Method

If value is String.Empty, the return value is 0.

And in LastIndexOf Method

If value is String.Empty, the return value is the last index position in this instance.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825