“Method1 hides inherited member Method2. Use the new keyword if hiding was intended” - Compiler Warning

Usually when we compile our C# code, sometimes we see a warning message in output window:

Method1 hides inherited member Method2. Use the new keyword if hiding was intended.

This warning means that Method1 is declared with the same name as a method in a base class. And the new is not used. This warning informs us that we should use new modifier.

using System;

namespace abc
{
   public class MyBaseClass
   {
      public int i = 1;
      public DataTable ViewCriteria()
      {
         //
      }
   }

   public class MyDerivedClass : MyBaseClass
  {
 
      public void ViewCriteria()  // Warning Line Code
      {
         // Some New Code For Derived Class
      }
   }
}

Here in above code, since we don't use a new keyword therefore we will face a warning during the code compilation. To remove the warning we need to add a new modifier as shown below.

      public new void ViewCriteria()  // Warning Line Code
      {
         // Some New Code For Derived Class
      }


The same would be applicable for a variable too as shown in below.
using System;

namespace abc
{
   public class MyBaseClass
   {
      public int i = 1;
      public DataTable BaseCriteria()
      {
         // Some Code For Base Method
      }
   }

   public class MyDerivedClass : MyBaseClass
  {
      public static int i = 1; // Warning Line Code

      public void DerivedCriteria()  
      {
         // Some Code For Derived Method
      }
   }
}

To avoid the warning, we need the following change in our code:

public static new int i = 1; // Warning Line Code

After applying new modifier, warning would be removed. :)

Comments

Popular posts from this blog

Data Bound Controls in ASP.Net - Part 4 (FormView and DetailsView controls)

ASP.net: HttpHandlers

The Clickjacking attack and X-Frame-Options