Cette page n'est pas encore disponible en français, sa traduction est en cours. Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.
Metadata
ID:csharp-best-practices/constant-expected
Language: C#
Severity: Info
Category: Best Practices
Description
The ConstantExpected rule in C# static analysis helps make sure constants are used correctly. Using constants incorrectly can lead to unexpected behavior, bugs, or security issues.
Apply the ConstantExpected attribute to parameters that should be constant within a range. This attribute has optional Min and Max parameters for the inclusive lower and upper bounds. The data type of Min and Max must match the parameter’s data type.
How to Remediate
To avoid violations, make sure the ConstantExpected attribute works with compatible parameter types and that Min and Max values are in the right order. The Min value must be less than or equal to Max. Also, Min and Max should fit within the parameter type’s limits. For instance, if the parameter is an ‘int’, Min and Max should also be ‘int’ and within the ‘int’ range. Following these practices makes your code stronger, easier to maintain, and less error-prone.
Non-Compliant Code Examples
// check https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1856// Violation - value not compatible with parameter type.staticvoidM1([ConstantExpected(Min="a")]charval){}staticvoidM1([ConstantExpected(Min="a",Max='b')]intval){}// Violation - unsupported type for attribute.staticvoidM2([ConstantExpected]decimalval){}// Violation - Min and Max values are inverted.staticvoidM3([ConstantExpected(Max=0,Min=1)]intval){}// Violation - value does not fit within the parameter value bounds.staticvoidM4([ConstantExpected(Min=long.MinValue)]intval){}