-3

I believed that doing an assignment operation inside an if condition's predicate would always result to true (in C# and in any other language). However, this doesn't happen when I tried something like this (Notice I'm just using single equals inside the If conditions):

class Program
    {
        static void Foo()
        {
            bool someVar = false;
            if (someVar = true)
                System.Diagnostics.Debug.WriteLine("This gets printed");  // as expected
        }

        static void Bar()
        {
            bool someVar = false;
            if (someVar = false)
                System.Diagnostics.Debug.WriteLine("This DOES NOT get printed");  // I exected this to be printed as well as it
        }

        static void Main(string[] args)
        {
            Foo();
            Bar();
        }
    }

Can anyone explain this? Is it because the variable someVar is being assigned a false value, its not going inside the if condition?

  • The result of an assignment expression is the value that was assigned. It allows you to chain assignments, e.g. `a = b = c`. If you were using an integer variable instead of a boolean, this would be more obvious; the compiler would complain that the expression inside the `if (...)` is not a boolean expression – Andrew Williamson Dec 03 '21 at 01:22
  • C# compiler should highlight your use of assignment rather than equality test. – Mitch Wheat Dec 03 '21 at 01:27
  • @MitchWheat This code doesn't result in any warnings or errors, so what "highlighting" are you expecting the compiler to provide? Of course, the question itself makes it clear that the use of the assignment operator is intentional, not unintentional, so even if it did highlight that fact, it doesn't answer the question of why it behaves this way. – Servy Dec 03 '21 at 01:51
  • In the curly-brace languages an assignment is not a statement but an expression. C# avoids most trouble with accidentally typing = instead of == in an if-statement, but not if the assignment expression type is bool. Since that's a valid condition type. – Hans Passant Dec 03 '21 at 01:51
  • @servy: not sure what IDE you're using, but my VS2019 won't compile an accidental assignment for equality test. – Mitch Wheat Dec 03 '21 at 02:31
  • @MitchWheat Then you have some 3rd party tool. The code shown has never failed to compile in any C# version, and given the policy on breaking changes they've generally followed, I can't imagine that ever changing. – Servy Dec 03 '21 at 14:04
  • @servy: I do not have any third party tools. – Mitch Wheat Dec 03 '21 at 23:37
  • @MitchWheat Then the code compiles just fine. It's one or the other. – Servy Dec 03 '21 at 23:54
  • As I said, I don't have a third party tool. In my haste to test it, I made the variable an int, and equality assignment then won't compile. – Mitch Wheat Dec 04 '21 at 00:21

3 Answers3

0

The code you present behave as expected: if (someVar = false) means you assign false to someVar and so the end result is if(false) which don't meet the condition.

G.Y
  • 6,042
  • 2
  • 37
  • 54
0

because the return value of (someVar = false) will be false

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 03 '21 at 01:26
-1

You can't use an assignment operator as the condition; equals is not the same as double equals! If you are evaluating for a condition, you have to compare with double equals. Given foo is a bool variable, this: foo = true; is an assignment. It assigns the value of foo to true. This: (foo == true) is not an assignment; it is instead a comparison. It will return the bool value of whether or not foo is currently assigned a value of true; if so, it will return true, else it will return false.

What is happening in your statement here is that instead using a comparison in the if() conditional, you are putting a variable in. Normally this isn't a problem, I can create foo and then have an if() statement that takes foo as the conditional, and it will check if foo is true or false. However, you are both passing the variable to the statement while simultaneously assigning it to a value. This is why foo as you have it set up will always print the statement, and bar always won't. You are doing the equivalent of setting foo to true and evaluating it, and likewise setting bar to false and evaluating that. :)

In other words, this:

bool bar = true;
if(bar = false) {
     doSomething;
}

is the same thing as doing this:

bool bar = true;
bar = false;
if(bar) {
     doSomething;
}

And therefore the code will never doSomething because bar is always set to false first.

  • 1
    "You can't use an assignment operator as the condition;" Well, I mean, you can. The question provides codes doing just that. The question author even makes it clear that they're doing so intentionally, not unintentionally. Why make a statement where the whole premise of the question you're trying to answer demonstrates it's false? Also, your assertion that the variable has its value read is also false. The variable's value is never read, even after the assignment. The assignment operator resolves to a value, which is subtly different, occasionally in relevant ways. – Servy Dec 03 '21 at 01:46
  • Well, you certainly CAN, but you shouldn't, since that is exactly what is causing the problems! If someone wants an if statement to always trigger, they should just say if(true) or if(1=1), or better yet not use an if statement at all and just have the internal code. This is a curious behavior, sure, but it results from extremely impractical coding practice. – Will Mungas Dec 14 '21 at 01:20
  • That's not what you said. You said can't, which is a statement of fact (in this case, an inaccurate one). Saying that they shouldn't is an opinion, and is an entirely separate issue from the actual question asked. – Servy Dec 14 '21 at 03:08
  • Fair enough; I should have said "You can't do so if you want it to work properly". – Will Mungas Sep 21 '22 at 23:55
  • There are plenty of programs working exactly as intended that use an assignment operation in a condition. That this particular person expected to resolve to a different value than it did doesn't mean there is never any use for the behavior that is actually correct. You may personally not like writing code that uses assignments in a condition (I tend to avoid them myself), and you're free to not use them, but saying you can't use them, or it can't work properly is just, again, a factually false statement. – Servy Sep 22 '22 at 15:18