user1555137
user1555137

Reputation: 37

Derived Class Cannot refer to parent class

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?

Upvotes: 0

Views: 168

Answers (1)

Prinzhorn
Prinzhorn

Reputation: 22508

You seem to misunderstand inheritance.

Every Daughter and every Son is a Father. That's why you can safely assign both to a Father variable. 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 Father and want to assign it to a Son variable, you can't be sure that the instance is a Son and actually has all the properties needed. The Father instance could as well contain a Daughter which is not compatible to Son. That's why the compiler can't implicitly convert them but you as a programmer can explicitly do it.

Upvotes: 1

Related Questions