Search code examples
c#debuggingif-statementvisual-studio-2013and-operator

How and Why is this If condition satisfying when value is false in C#


I have this strange problem in Windows Phone Application. Hitting hardware Back button exits the application when it should have shown the previous page. While debugging, I found something really strange.

If Condition satisfied for false

In this method, this.Frame is Not null (as shown in 3rd pin) but this.Frame.CanGoBack is False (as shown in 1st pin) which means the && (AND) operator should make this condition as false and it does (as shown in the second Pin). Still debugger stepped in the condition to execute(as you can see below second pin).

This is really strange and This only exits my application.


Solution

  • The this.Frame.CanGoBack property changed between the time it entered and the time it got to the next line. A property that is implemented like the following:

    get {
       var result=backingvalue;
       backingvalue=!result;
       return result;
    }
    

    Would do it.

    Try changing the code to the following:

    var bool1=this.Frame!=null;
    if (bool1)
    {
      var bool2=this.Frame.CanGoBack;
      if (bool2)
      {
        ...
      }
    }
    

    Then put a breakpoint and check the values of bool1/bool2 as well as this.Frame.CanGoBack.