IndexOf method returns 0 when it should had return -1 in C# / Java

jcgarciam picture jcgarciam · Apr 2, 2010 · Viewed 7.8k times · Source

A friend of mine came to me with this strange behavior which i can't explain, any insight view would be appreciated.

Im running VS 2005 (C# 2.0), the following code show the behavior

int rr = "test".IndexOf("");
Console.WriteLine(rr.ToString());

the above code, print "0" which clearly show it should have return -1

This also happen in Java where the following Class show the behavior:

public class Test{
 public static void main(String[] args){
   System.out.println("Result->"+("test".indexOf("")));
 }
}

Im running Java 1.6.0_17

Answer

Fredrik Mörk picture Fredrik Mörk · Apr 2, 2010

Quote from the C# documentation:

If value is Empty, the return value is 0.

The behavior that you describe is entirely as expected (at least in C#).