다음을 통해 공유


CA1500: Variable names should not match field names

Note

This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

For the latest documentation on Visual Studio, see CA1500: Variable names should not match field names.

Item Value
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 cannot be seen outside the assembly, regardless of the change you make.
- Breaking - If you change the name of the field and can be seen outside the assembly.
- Breaking - If you change the name of the parameter and the method that declares it can be seen outside the assembly.

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

- Non-breaking - If the field cannot be seen 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 can be seen outside the assembly.

Cause

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 by using debugging information and the associated program database (.pdb) file must be available.

Rule Description

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. When maintaining code, it is easy to forget this difference and assume that the parameter/local variable refers to the instance field, which leads to errors. This is true especially for lengthy method bodies.

How to Fix Violations

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

When to Suppress Warnings

Do not suppress a warning from this rule.

Example

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;
      }
   }
}
Imports System

Namespace MaintainabilityLibrary

   Class MatchingNames
   
      Dim someField As Integer
   
      Sub SomeMethodOne(someField As Integer)
      End Sub
      
      Sub SomeMethodTwo()
         Dim someField As Integer
      End Sub
      
   End Class
   
End Namespace