Primal Scream

Every have one of those days were it seems like the world is secretly trying to scramble your brains? I'm having one today.
For some reason this statement compiles just fine:

if(anyYearCheck.Checked = false && (1 > 2))

{

}

Did you notice the problem? Yeah? Well I didn't.
 
For those like me who didn't catch it, here is the deal; "Checked = false" doesn't check the value of Checked, it sets the value of Checked. So rather than checking for false I was setting it to false. This caused some rather intricate four-letter-word sentences to be expunged by yours truly.
 
What I find odd is that I'm positive that statements like this have cause compiler errors in the past. So like I said, the world must be secretly out to get me.
 
UPDATED: My code sample was wrong. This error requires the && to be included in the if statement.

6 Comments

  • thats why i prefer:



    if (false == someCheckBox.Checked)



    Because



    if (false = someCheckBox.Checked)



    Doesnt compile, right?

  • Yeah, that will toss the compile error. But I'm not sure I like the way that reads. It looks a little off.

  • I don't understand why boolean properties or members or other variables need to be compared against 'false' or 'true'.



    I'd simply write:



    if(!anyYearCheck.Checked && (1 > 2))

    {

    }



    To me, boolean properties, member fields and other boolean variables should always have a name that implies they're booleans. Like Checked, IsBlacklisted, HasChildren etc...



    My 2 cents,

    Wim

  • Ok,



    if( (!anyYearCheck.Checked) && (1 > 2))

    {

    }



    ...me thinks...

  • I agree, the ! would have solved my problem, and I normally would have used it.



    This time however it was in a large collection of assorted validations prior to saving the data. In these cases, where you are checking a large number of different variables, I dislike using a ! because it can often be missed when reading the code. Thus the explicit use of == false.



  • >Yeah, that will toss the compile error. But I'm not sure I like the way that reads. It looks a little off.



    I know how you feel. But I made "the switch" a few years back after

    reading Code Complete (S. McConnell) and I've got used to it now.

    And it has saved me a lot of head-wrecking...

Comments have been disabled for this content.