Total .NET Analyzer Rule Documentation  

AssignmentToParameter Rule

Avoid assigning values to parameters.

Remarks

In general, you should avoid assigning values to parameters. Assigning values to parameters can cause confusion during code review, as it may not be immediately clear whether the parameter was passed by value (changes do not persist in the calling routine) or by reference (changes persist to caller). In order to keep the code easy to read and understand, the value of the parameter that is passed in should remain constant.

For example, the following code modifies both of the parameters that are passed.


Public Function CountDown(ByVal startNumber As Integer, ByVal countNumber As Integer) As Integer
Do While countNumber > 0
startNumber -= 1
countNumber -= 1
Loop
Return startNumber
End Function

// C#
public static int CountDown(int startNumber, int countNumber)
{
while (countNumber > 0)
{
startNumber -= 1;
countNumber -= 1;
}
return startNumber;
}

Resolution

Instead of assigning a value to the parameter, you should create a temporary variable for the parameter. Any necessary assignments should be made to the temporary variable. For instance, you could modify the code example above to:


Public Function CountDown(ByVal startNumber As Integer, ByVal countNumber As Integer) As Integer
Dim counter As Integer = countNumber
Dim result As Integer = startNumber
Do While countNumber > 0
result -= 1
counter -= 1
Loop
Return result
End Function

// C#
public static int CountDown(int startNumber, int countNumber)
{
int counter = countNumber;
int result = startNumber;
while (counter > 0)
{
result -= 1;
counter -=1;
}
return result;
}

See Also

Argument Passing