No warning/message about possible assignment in conditional expression CS0665

This:

bool b1 =true;
bool b2 =true;
if (b1=true)
{} 

Gives warning about Assignment in conditional expression

This does not:

bool b1 =true;
bool b2 =true;
if ((b1=true) && (b2=true))    {}

Why?

JetBrains Rider 2023.3.3

Build #RD-233.14015.60, built on January 18, 2024

0
3 comments
Hello,

Thank you for contacting Rider support.

This is because "=" is the assignment operator. The comparison operator in C# and C++ is "==".
The sample you shared will always be true, whatever value you would assign to the variables before comparing them somehow:

bool b1 =false;
bool b2 =false;
if ((b1=true) && (b2=true))    { /* execution goes here anyway, b1=b2=true already*/ }

If you would write as above, still the conditional expression returns true. Moreover, inside "{}" b1, b2 will be having value 'true'.

The proper code will be:

if((b1==true)&&(b2==true)) {}

Also, it can be shorten into if(b1&&b2) {}

Hope that helps.
Have a nice day!
0

Can Rider at least warn me that maybe I meant == instead of = in case of 2 or more Assignment in conditional expressions?

So when it see code like 

bool b1 =true;
bool b2 =true;
if ((b1=true) && (b2=true))    {}

it can warn me about possible CS0665 error?

0

Hello,

Thank you for comming back. I have read the question one more time and realised that I misunderstood the question. Apologies for the confusion made and didn't double-checked the IDE behavior.

Answering the question why the inspection triggers in if(b1=true) {} but not in if((b1=true)&&(b2=true)).

As a fact this is a compiler warning. Rider just reproduces this behavior. Since compiler doesn't see any problems in  if((b1=true)&&(b2=true)), Rider doesn't report that.

The C# compiler in .NET doesn't complain about an assignment within a conditional expression as long as it's explicitly enclosed in parentheses - which is the case for ((b1=true) && (b2=true)). This is because the parentheses clarify the developer's intention of making an assignment, rather than a presumed typo of ==.

Rider is not alone in that behavior. For example, VS and sharplab.io behaves the same.

Hope I answered the question.

Have a nice day!

 

 

 

0

Please sign in to leave a comment.