class Program
{
static void Main(string[] args)
{
Father objFather = new Son(); //Ok compiles
Son objSon1 = new Father(); //Comile time error : Cannot implicitly convert type
Son objSon = (Son)new Father(); //Run time error
Console.ReadLine();
}
}
class Father
{
public void Read()
{
}
}
class Daughter:Father
{
}
class Son:Father
{
}
Can anybody Explain why it is? And what is happening in memory?
You seem to misunderstand inheritance.
Every
Daughterand everySonis aFather. That’s why you can safely assign both to aFathervariable. A subclass can’t remove attributes/methods only add them, that’s why it’s sure it’s always working.But when you have an instance of
Fatherand want to assign it to aSonvariable, you can’t be sure that the instance is aSonand actually has all the properties needed. TheFatherinstance could as well contain aDaughterwhich is not compatible toSon. That’s why the compiler can’t implicitly convert them but you as a programmer can explicitly do it.