Why explicit conversion required to assign base class to derived class? But not required to do the reverse

paul sim picture paul sim · Dec 16, 2011 · Viewed 10.9k times · Source

I have a base class and a derived class as bellow

public class animal
{
    public string name { get; set; }
}

public class dog : animal
{
    public int age { get; set; }
    public string type { get; set; }
}

uses:

animal a = new animal();

dog d = new dog();

a = d; //compiled

d = a; //Error:Cannot implicitly convert type 'animal' to 'dog'.

d = (dog)a; // compiled

What happen internally that derived class can assigned to base but doing the reverse explicit conversion is required? Same result found even both base and derived class contains same member.

Answer

Marty picture Marty · Dec 16, 2011

All dogs are animals, but not all animals are dogs. Implicit conversion is not allowed because your a might not actually be a d.