Skip to content

Gendarme.Rules.Correctness.AvoidCodeWithSideEffectsInConditionalCodeRule(2.10)

Sebastien Pouliot edited this page Jan 22, 2011 · 2 revisions

AvoidCodeWithSideEffectsInConditionalCodeRule

Assembly: Gendarme.Rules.Correctness
Version: 2.10

Description

A number of System methods are conditionally compiled on #defines. For example, System.Diagnostics.Trace::Assert is a no-op if TRACE is not defined and System.Diagnostics.Debug::Write is a no-op if DEBUG is not defined. When calling a conditionally compiled method care should be taken to avoid executing code which has visible side effects. The reason is that the state of the program should generally not depend on the value of a define. If it does it is all too easy to create code which, for example, works in DEBUG but fails or behaves differently in release. This rule flags expressions used to construct the arguments to a conditional call if those expressions write to a local variable, method argument, or field. This includes pre/postfix increment and decrement expressions and assignment expressions.

Examples

Bad example:

internal sealed class Helpers {
    public string StripHex (string text)
    {
        int i = 0;
        // This code will work in debug, but not in release.
        Debug.Assert (text [i++] == '0');
        Debug.Assert (text [i++] == 'x');
        return text.Substring (i);
    }
}

Good example:

internal sealed class Helpers {
    public string StripHex (string text)
    {
        Debug.Assert (text [0] == '0');
        Debug.Assert (text [1] == 'x');
        return text.Substring (2);
    }
}
Clone this wiki locally