Export (0) Print
Expand All

Variable names should not match field names

TypeName

VariableNamesShouldNotMatchFieldNames

CheckId

CA1500

Category

Microsoft.Maintainability

Breaking Change

When fired on a parameter that has the same name as a field:

  • Non Breaking - If both the field and method that declares the parameter are not visible outside the assembly, regardless of the change you make.

  • Breaking - If you change the name of the field, and it is visible outside the assembly.

  • Breaking - If you change the name of the parameter, and the method that declares it is visible outside the assembly.

When fired on a local variable that has the same name as a field:

  • Non Breaking - If the field is not visible outside the assembly, regardless of the change you make.

  • Non Breaking - If you change the name of the local variable and do not change the name of the field.

  • Breaking - If you change the name of the field and it is visible outside the assembly.

An instance method declares a parameter or a local variable whose name matches an instance field of the declaring type. To catch local variables that violate the rule, the tested assembly must be built with debugging information and the associated program database (.pdb) file must be available.

When the name of an instance field matches a parameter or a local variable name, the instance field is accessed by using the this (Me in Visual Basic) keyword when inside the method body. While maintaining code, it is easy to forget this difference and assume that the parameter/local variable refers to the instance field, leading to errors. This is true especially for lengthy method bodies.

To fix a violation of this rule, rename either the parameter/variable or the field.

Do not suppress a warning from this rule.

The following example shows two violations of the rule.

using System;

namespace MaintainabilityLibrary
{
   class MatchingNames
   {
      int someField;

      void SomeMethodOne(int someField) {}

      void SomeMethodTwo()
      {
         int someField;
      }
   }
}

Although this rule does not fire on constructors, it will fire on the someField parameter declared in the Init method in the following common pattern:

using System;

namespace MaintainabilityLibrary
{    
    class MatchingNames    
    {        
        int someField;

        public MatchingNames(int someField) // Does not violate VariableNamesShouldNotMatchFieldNames             {            
            Init(someField);        
        }

        private void Init(int someField)  // Violates VariableNamesShouldNotMatchFieldNames        
        {            
            this.someField = someField;        
        }    
    }
}

Community Additions

ADD
Show:
© 2014 Microsoft