CA1856: Incorrect usage of ConstantExpected attribute
Property | Value |
---|---|
Rule ID | CA1856 |
Title | Incorrect usage of ConstantExpected attribute |
Category | Performance |
Fix is breaking or non-breaking | Non-breaking |
Enabled by default in .NET 8 | As error |
Cause
The ConstantExpectedAttribute attribute is not applied correctly on a parameter.
Rule description
This rule flags incorrect uses of the ConstantExpectedAttribute attribute, such as:
- The Min or Max value isn't compatible with the parameter type.
- The parameter type isn't supported for the ConstantExpectedAttribute attribute.
- The Min and Max values are inverted.
- The Min or Max value doesn't fit within the parameter value bounds.
How to fix violations
Correct your code as indicated by the specific error message you receive.
Example
The following code snippet shows violations of CA1856:
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) { }
The following code snippet fixes the violations:
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 warnings
A violation of this rule indicates an error in your code, and should always be fixed.
Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.
Feedback
https://aka.ms/ContentUserFeedback.
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see:Submit and view feedback for