Link to home
Start Free TrialLog in
Avatar of shekhar_shashi
shekhar_shashi

asked on

C# Issue: bool values sets itself to true

I am developing C# code for a .Net 4.0 Windows Forms project using VS 2010.

I have a very simple method that seems to return true even if it should return false (I think).

bool ShouldControlBeReenabled(Control c)
        {
          bool _ShouldControlReEnabled = false;
            if ((c is JISButton) && ((JISButton)c).ButtonStyle == JISButton.ButtonMode.Cancel)
                _ShouldControlReEnabled = true;
            return _ShouldControlReEnabled;
        }

While debugging the code, I noticed that the bool value initializes to false. The if condition evaluates to false and the third line (_ShouldControlReEnabled = true;)  does not get executed. But for some bizarre reason, the _ShouldControlReEnabled sets itself to true. Not sure what is going on.

A bool variable should default to false and should stay false unless the if conditon evaluates to true. So what I am seeing is really unbelievable. There are no exceptions in the if condition or the method execution.

Please help me figure out whats going on. Thanks experts for your help.
SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of shekhar_shashi
shekhar_shashi

ASKER

There is no more code relevant to the problem. All the logic is in this method itself. I changed the code to do multiple returns (@idle_minds's solution) and it meets my requirements. However, I am curious to know why the bool variable resets itself. I'll surely accept your solution(s) and reward points but this behavior is bothering me.
I am also interested - what does this do

bool ShouldControlBeReenabled(Control c)
{
   bool _ShouldControlReEnabled = false;
   return _ShouldControlReEnabled;
}
Or even this

bool ShouldControlBeReenabled(Control c)
{
   bool _ShouldControlReEnabled = false;
   if (1 == 0) {
      _ShouldControlReEnabled = true;
   }
   return _ShouldControlReEnabled;
}
@JulianH - your methods work as expected. They both return false. I tried another flavor of your methods and the return value is was again false (as expected). My best guess is that there is something special about the boolean expression in my original code. Even though the expression evaluates to false in Visual Studio Debugger, there is something else going on in MSIL that I am not aware of. It could be a .Net bug. So I think I'll close the post and reward the points.

Thanks @JulianH and @Idle_Mind.
You are welcome