New Rule: NoAssignmentInsideConditionals

Developer
Apr 6, 2011 at 6:14 AM
Edited Apr 6, 2011 at 6:35 AM

To carry on the side topic at http://stylecop.codeplex.com/discussions/252502...

StyleCop does not currently complain about either of the following code patterns.  Where bb and cc are bools:

if (bb = cc)
{
    // ...
}

while (bb = cc)
{
    // ...
}

if ((a = b) > 3)
{
    // ...
}

while ((a = b) < 4)
{
    // ...
}

switch (bb = cc)
{
    case true:
    default:
}
I believe the pattern shown by the first two assignments-inside-conditionals can sometimes be a typo/mistake, and if not by a mistake the coder, could easily get mistaken by maintainers scanning over it as a comparison operator.  Fortunately this isn't a very common problem since it generally only applies to bools.  However, all of these examples have more straight-forward, logical implementations by pulling the assignments into their own lines of code.  The "shortcuts" being employed by allowing the assignment to be within conditionals are unnecessary and I think we should provide a rule to call this out.
Apr 8, 2011 at 3:07 PM

Whilst this will require careful consideration, this looks to be a good idea.

Coordinator
Apr 15, 2011 at 9:08 AM
This discussion has been copied to a work item. Click here to go to the work item and continue the discussion.