Skip to content

Gendarme.Rules.BadPractice.ReplaceIncompleteOddnessCheckRule(git)

Sebastien Pouliot edited this page Mar 2, 2011 · 1 revision

ReplaceIncompleteOddnessCheckRule

Assembly: Gendarme.Rules.BadPractice
Version: git

Description

This rule checks for problematic oddness checks. Often this is done by comparing a value modulo two (% 2) with one (1). However this will not work if the value is negative because negative one will be returned. A better (and faster) approach is to check the least significant bit of the integer.

Examples

Bad example:

public bool IsOdd (int x)
{
    // (x % 2) won't work for negative numbers (it returns -1)
    return ((x % 2) == 1);
}

Good example:

public bool IsOdd (int x)
{
    return ((x % 2) != 0);
}

Good example (faster):

public bool IsOdd (int x)
{
    return ((x & 1) == 1);
}

Notes

  • This rule is available since Gendarme 2.0

Source code

You can browse the latest source code of this rule on github.com

Clone this wiki locally