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.
When you use explicit conversion, in your case, you are telling the compiler that you know what is going on. If you were to compile your code, removing
d = a;, and you tried to access a public member ond, and exception would be thrown. That is because, in this instance, theanimalis not adog. You explicitly created ananimaland assigned it toa.Explicit conversion allows you to do thing when you know the conversion will work.
In this case, we know that
MyAnimalis actually adog, so we can do an explicit cast to it. All of this works because of inheritance. Because inheritance does not work both ways, the complier will not allow an implicit up cast–you must do it explicitly.We know that when a class inherits from its base class, it takes with it the public properties and methods. You cannot say that your reference to an
animalwill always contain the properties and methods of adog.