Share via


CA1061: Do not hide base class methods

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

Item Value
TypeName DoNotHideBaseClassMethods
CheckId CA1061
Category Microsoft.Design
Breaking Change Breaking

Cause

A derived type declares a method with the same name and with the same number of parameters as one of its base methods; one or more of the parameters is a base type of the corresponding parameter in the base method; and any remaining parameters have types that are identical to the corresponding parameters in the base method.

Rule Description

A method in a base type is hidden by an identically named method in a derived type when the parameter signature of the derived method differs only by types that are more weakly derived than the corresponding types in the parameter signature of the base method.

How to Fix Violations

To fix a violation of this rule, remove or rename the method, or change the parameter signature so that the method does not hide the base method.

When to Suppress Warnings

Do not suppress a warning from this rule.

Example

The following example shows a method that violates the rule.

using System;
  
namespace DesignLibrary
{
   class BaseType
   {
      internal void MethodOne(string inputOne, object inputTwo)
      {
         Console.WriteLine("Base: {0}, {1}", inputOne, inputTwo);
      }

      internal void MethodTwo(string inputOne, string inputTwo)
      {
         Console.WriteLine("Base: {0}, {1}", inputOne, inputTwo);
      }
   }

   class DerivedType : BaseType
   {
      internal void MethodOne(string inputOne, string inputTwo)
      {
         Console.WriteLine("Derived: {0}, {1}", inputOne, inputTwo);
      }

      // This method violates the rule.
      internal void MethodTwo(string inputOne, object inputTwo)
      {
         Console.WriteLine("Derived: {0}, {1}", inputOne, inputTwo);
      }
   }

   class Test
   {
      static void Main()
      {
         DerivedType derived = new DerivedType();

         // Calls DerivedType.MethodOne.
         derived.MethodOne("string1", "string2");

         // Calls BaseType.MethodOne.
         derived.MethodOne("string1", (object)"string2");

         // Both of these call DerivedType.MethodTwo.
         derived.MethodTwo("string1", "string2");
         derived.MethodTwo("string1", (object)"string2");
      }
   }
}