Skip to content

Latest commit

 

History

History
78 lines (61 loc) · 1.79 KB

SA1131.md

File metadata and controls

78 lines (61 loc) · 1.79 KB

SA1131

TypeName SA1131UseReadableConditions
CheckId SA1131
Category Readability Rules

📝 This rule is new for StyleCop Analyzers, and was not present in StyleCop Classic.

Cause

A comparison was made between a variable and a literal or constant value, and the variable appeared on the right-hand side of the expression.

Rule description

A violation of this rule occurs whenever the code contains a comparison between a literal or constant value and a variable value, and the variable appeared on the right-hand side of the expression.

For example, the following code shows one commonly-seen case of this:

public void Method(string value)
{
    if (null == value) // SA1131
    {
        throw new ArgumentNullException(nameof(value));
    }
}

For the purposes of this rule, a literal or constant value is any of the following:

  • A numeric literal, such as 1, 0.0f, or 5.0m
  • A string literal
  • null
  • default(T) (for any type T)
  • Any expression which evaluates to a constant value at compile time
  • A reference to a static readonly field, such as IntPtr.Zero

A variable value is any expression which is not considered a literal or constant value.

A comparison is a binary expression using one of the following operators.

  • ==
  • !=
  • <
  • >
  • <=
  • >=

How to fix violations

To fix a violation of this rule, reverse the order of operands to the comparison.

How to suppress violations

public void Method(string value)
{
#pragma warning disable SA1131 // Use readable conditions
    if (null == value)
#pragma warning restore SA1131 // Use readable conditions
    {
        throw new ArgumentNullException(nameof(value));
    }
}