1

I have this code. I dont understand why the derived class's print isnt called. I believe it is because of 'new'. Which I am not sure of its functionality.

using System;
class BaseClass
{
  public void Print()
  {
     System.Console.WriteLine("BaseClass");
  }
}

class DerivedClass : BaseClass
{
  new public void Print()
  {
     System.Console.WriteLine("DerivedClass");
  }
}

class Program
{
  public static void Main()
  {
     BaseClass b;
     b = new BaseClass();
     b.Print();   

     b = new DerivedClass();
     b.Print();    
  }
}
Ilan Aizelman WS
  • 1,630
  • 2
  • 21
  • 44

2 Answers2

3

Because the Print method is not virtual and you explicitly mark it as totally independent from the base class' one with the new keyword. Change the method to virtual and override it in the derived class:

class BaseClass
{
  public virtual void Print()
  {
     System.Console.WriteLine("BaseClass");
  }
}

class DerivedClass : BaseClass
{
  public override void Print()
  {
     System.Console.WriteLine("DerivedClass");
  }
}
Dmitry Egorov
  • 9,542
  • 3
  • 22
  • 40
  • I see, because in java it would work(all functions are virtual by default). C# is a bit different in that. Thanks Dmitry! – Ilan Aizelman WS May 16 '17 at 15:16
  • Btw, in your example, if instead of override I write 'new', it will just hide the print function in the base class, thus it will call the base's print and hide it from the derived class. – Ilan Aizelman WS May 16 '17 at 15:24
0

Yes because your b is BaseClass Type and you have not virtual function Print in it and as you have not you can't override it in DerivedClass and will be called BaseClass Print().

Samvel Petrosov
  • 7,580
  • 2
  • 22
  • 46