Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2005
 Variable names should not match fie...

  Switch on low bandwidth view
This page is specific to
Microsoft Visual Studio 2005/.NET Framework 2.0

Other versions are also available for the following:
Visual Studio Team System
Variable names should not match field names

TypeName

VariableNamesShouldNotMatchFieldNames

CheckId

CA1500

Category

Microsoft.Maintainability

Breaking Change

Breaking,NonBreaking

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 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. Note that it is a breaking change to rename an externally visible field or a parameter in an externally visible method.

Do not exclude a warning from this rule.

The following example shows two violations of the rule.

Visual Basic
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
C#
using System;

namespace MaintainabilityLibrary
{
   class MatchingNames
   {
      int someField;
   
      void SomeMethodOne(int someField) {}
      
      void SomeMethodTwo()
      {
         int someField;
      }
   }
}
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Does not fire on constructors      David M. Kean   |   Edit   |   Show History

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:

[C#]
 
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;
        }
    }
}
Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker