onsdag, oktober 25, 2006

Dont trust your debugger

I just waisted a couple of hours because of a strange behaviour in the Visual Studio debugger.
Consider the following code:

object
obj = new String('a',1); //"a"
string str = new String('a',1); //"a"
Console.Out.WriteLine(obj == str); //ln1
Console.Out.WriteLine(str == obj); //ln2
Console.Out.WriteLine((string)obj == str);//ln3
Console.Out.WriteLine(str ==(string)obj); //ln4
Console.Out.WriteLine(obj.Equals(str)); //ln5
Console.Out.WriteLine(str.Equals(obj)); //ln6

Now, add breakpoints in Visulal Studio on line 1 to 6 - and make the debugger evaluate the expression before it is printet to the console.


What would you (the debugger) expect the output to be? The Visual Studio Debugger says:
true
true
true
true
true
true


This is however not the case. The actual output is:
false
false
true
true
true
true


There is really nothing strange about the result. The == operator does not just call the Equals method blindly and virtually as one might expect. It is actually an operator that compares references unless overridden.

By default the == operator compares for reference equality. So if == tests for reference equality, this would explain the behavior of the result of ln1 and ln2, but not ln 3 and 4. This is because the == operator has been overridden in the String class to call the Equals method, thus comparing the value of the string rather than its reference. (this explains ln 3 and 4).

The runtime system determines which operator to call based on the runtime type (the type of the reference rather than the type of the instance). In ln 1 and 2 the == operator of the Object class is used, where in ln3 and ln4 the operator as defined in the String class is used.

So much for the == operator. The strange thing however, is that the Visual Studio debugger does not seam to get this. (VS2003). I used a lot of time debugging an expression inside an 'if' statement, which evaluated to false (by the debugger) but the if - statement - body was entered anyway. Grrr – I’m a bit pissed at the debugger.

Ingen kommentarer: