Constants are similar to variables, except that you are not allowed to assign new values to them. If you do not need to modify or assign a value to a variable, consider changing it to a constant. Using constants for values that do not change in code makes your code easier to understand and maintain.
Note that this rule is flagged when a specific use of the variable always has the same value. It does not necessarily mean that you can simply change the variable to a constant. In this case, you may want to create a new constant for this use.
In the following example, the variable pi should be a constant, since it is not modified in code:
' VB
Function CalcArea(ByVal radius As Double) As Double
Dim pi As Double = 3.14159
Return pi * radius * radius
End Function
// C#
static double CalcArea(double radius)
{
double pi = 3.14159;
return pi * radius * radius;
}
' VB
Function CalcArea(ByVal radius As Double) As Double
Const pi As Double = 3.14159
Return pi * radius * radius
End Function
// C#
static double CalcArea(double radius)
{
const double pi = 3.14159;
return pi * radius * radius;
}