The base method must be declared as virtual
if you want to override
it in a child class:
class BaseClass
{
public virtual string SayHi()
{
return ("Hi");
}
}
class DerivedClass : BaseClass
{
public override string SayHi()
{
return (base.SayHi() + " from derived");
}
}
If the base method is not declared as virtual you will actually get a compiler warning telling you that you are trying to hide this base method. If this is your intent you need to use the new
keyword:
class BaseClass
{
public string SayHi()
{
return ("Hi");
}
}
class DerivedClass : BaseClass
{
public new string SayHi()
{
return (base.SayHi() + " from derived");
}
}
UPDATE:
To better see the difference between the two take a look at the following examples.
The first one using a base virtual method which is overriden in the child class:
class BaseClass
{
public virtual string SayHi()
{
return ("Hi");
}
}
class DerivedClass : BaseClass
{
public override string SayHi()
{
return (base.SayHi() + " from derived");
}
}
class Program
{
static void Main()
{
BaseClass d = new DerivedClass();
// the child SayHi method is invoked
Console.WriteLine(d.SayHi()); // prints "Hi from derived"
}
}
The second hiding the base method:
class BaseClass
{
public string SayHi()
{
return ("Hi");
}
}
class DerivedClass : BaseClass
{
public new string SayHi()
{
return (base.SayHi() + " from derived");
}
}
class Program
{
static void Main()
{
BaseClass d = new DerivedClass();
// the base SayHi method is invoked => no polymorphism
Console.WriteLine(d.SayHi()); // prints "Hi"
}
}