AssignmentToParameter

AssignmentToParameter

Summary

Assignment to parameters must be avoided.

Default severity

Warning

Description

This rule reports diagnostic information of assignment to the parameters passed by value (except by reference). Note that [1]:

Do not confuse the concept of passing by reference with the concept of reference types. The two concepts are not the same. A method parameter can be modified by ref regardless of whether it is a value type or a reference type. There is no boxing of a value type when it is passed by reference.

Those who are unfamiliar with C# often assign a new value to the parameters passed by value, with the intention that the assignment will be reflected in the caller's variables. This rule allows them to immediately notice that they confused or misled themselves.

The diagnostic for a parameter passed by value is reported when the method does as follows:

  • Assign a new value to it
  • Increment or decrement it
  • Pass it to any method as the ref or out parameter.

Code fix

The code fix is not provided.

Example

Diagnostic

public int Method(int length)
{
    if (length < 0)
    {
        length = 0;
    }
    length += 1;

    ++length;
    --length;

    OtherMethod(ref length);
    AnotherMethod(out length);
    ⋮

See also

  • Remove Assignments To Parameters [2]

  • ParameterAssignment [3]

    Disallows assignment of parameters.

    Rationale: Parameter assignment is often considered poor programming practice. Forcing developers to declare parameters as final is often onerous. Having a check ensure that parameters are never assigned would give the best of both worlds.

  • FinalParameters [3]

    Check that parameters for methods, constructors, and catch blocks are final. Interface, abstract, and native methods are not checked: the final keyword does not make sense for interface, abstract, and native method parameters as there is no code that could modify the parameter.

    Rationale: Changing the value of parameters during the execution of the method's algorithm can be confusing and should be avoided. A great way to let the Java compiler prevent this coding style is to declare parameters final.

References

[1] Microsoft, ref keyword (C# Reference)

[2] Fowler, Martin, et al. Refactoring: improving the design of existing code. Addison-Wesley Professional, 1999.

[3] Checkstyle