All rules
CA1856Performance Enabled by default: As error

Incorrect usage of ConstantExpected attribute

Incorrect usage of ConstantExpected attribute

Microsoft docs

Description

This rule flags incorrect uses of the System.Diagnostics.CodeAnalysis.ConstantExpectedAttribute attribute, such as:

  • The System.Diagnostics.CodeAnalysis.ConstantExpectedAttribute.Min or System.Diagnostics.CodeAnalysis.ConstantExpectedAttribute.Max value isn't compatible with the parameter type.
  • The parameter type isn't supported for the System.Diagnostics.CodeAnalysis.ConstantExpectedAttribute attribute.
  • The System.Diagnostics.CodeAnalysis.ConstantExpectedAttribute.Min and System.Diagnostics.CodeAnalysis.ConstantExpectedAttribute.Max values are inverted.
  • The System.Diagnostics.CodeAnalysis.ConstantExpectedAttribute.Min or System.Diagnostics.CodeAnalysis.ConstantExpectedAttribute.Max value doesn't fit within the parameter value bounds.

Cause

The System.Diagnostics.CodeAnalysis.ConstantExpectedAttribute attribute is not applied correctly on a parameter.

How to fix violations

Correct your code as indicated by the specific error message you receive.

Example

using System.Diagnostics.CodeAnalysis;

// Violation - value not compatible with parameter type.
static void M1([ConstantExpected(Min = "a")] char val) { }
// Violation - unsupported type for attribute.
static void M2([ConstantExpected] decimal val) { }
// Violation - Min and Max values are inverted.
static void M3([ConstantExpected(Max = 0, Min = 1)] int val) { }
// Violation - value does not fit within the parameter value bounds.
static void M4([ConstantExpected(Min = long.MinValue)] int val) { }

using System.Diagnostics.CodeAnalysis;

static void M1([ConstantExpected(Min = 'a')] char val) { }
static void M2(decimal val) { }
static void M3([ConstantExpected(Min = 0, Max = 1)] int val) { }
static void M4([ConstantExpected(Min = int.MinValue)] int val) { }

When to suppress

A violation of this rule indicates an error in your code, and should always be fixed.

Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0