As referenced in this MSDN article:
The type object of derived class has no access to the new re-defined method inherited from base class and the call on an object of derived class from ShowDetails()
Method inside the inherited Method DescribeCar()
is made to the ShowDetails()
Method of base class.
if the DescribeCar()
Method is also available to the ConvertibleCar
class, How come it cannot see the so-called new ShowDetails()
Method?
class Car
{
public void DescribeCar()
{
System.Console.WriteLine("Four wheels and an engine.");
ShowDetails();
}
public virtual void ShowDetails()
{
System.Console.WriteLine("Standard transportation.");
}
}
// Define the derived classes.
// Class ConvertibleCar uses the new modifier to acknowledge that ShowDetails
// hides the base class method.
class ConvertibleCar : Car
{
public new void ShowDetails()
{
System.Console.WriteLine("A roof that opens up.");
}
}
class Program
{
static void Main(string[] args)
{
ConvertibleCar car2 = new ConvertibleCar();
car2.DescribeCar();
}
}
//output
// Four wheels and an engine.
// Standard transportation.
new
hides the old method, which means that if you directly call it on a ConvertibleCar
instance, you will get the derived class behavior, but it won't be called polymorphically.
When the base class calls it, it is calling the virtual method, which since it hasn't been overridden invokes the base class method. Instead of using method hiding (which you almost never use anyways), just override it:
class ConvertibleCar : Car
{
public override void ShowDetails()
{
System.Console.WriteLine("A roof that opens up.");
}
}