Avoiding assignment vs. equality bugs
Here’s a quick tip to help prevent bugs caused by confusion between the C# equality operator (“==”) and the assignment operator (“=”). Although the compiler will issue a warning, it’s still possible to compile code like this:
bool flag = true;
if (flag = false) { /* do something */ }
The intention is to test whether the value of flag is false, but instead the value false is assigned to the variable flag. I’m sure every programmer’s done it, especially if you come from a BASIC background where the assignment and equality operators are both “=”.
It seems counterintuitive, but try putting the literal constant operand on the left:
if (true == flag) { /* do something */ }
Now, if you accidently use “=” instead of “==” then it doesn’t matter because the code won’t compile and you’ll easily spot the mistake; the left hand side of an assigment must always be a variable.