Is there any relation between Liskov Substitution Principle and Method hiding in c#?
The Liskov Substitution Principle says the object of base class can be substituted/replaced by its object of derived class.
Lets take an example `using System;
namespace Polymorphism
{
class A
{
public void Test() { Console.WriteLine(“A::Test()”); }
}
class B : A
{
public new void Test() { Console.WriteLine("B::Test()"); }
}
class C : B
{
public new void Test() { Console.WriteLine("C::Test()"); }
}
class Program
{
static void Main(string[] args)
{
A a = new A();
B b = new B();
C c = new C();
a.Test();
b.Test();
c.Test();
a = new B();
a.Test();
b = new C();
b.Test();
Console.ReadKey();
}
}
}
Here A a = new A();
a.Test(); // will produce the result A::Test()
Now on the following line of code will produce the same result but using the derived class B of the base class A.
a = new B();
a.Test(); // will produce the result A::Test()
So it is very clear that the object a of the base class A is replaceable by instance of the object B() which is derived from A.