Search code examples
c#typesvariable-assignmentradixderived

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


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.


Solution

  • 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 on d, and exception would be thrown. That is because, in this instance, the animal is not a dog. You explicitly created an animal and assigned it to a.

    Explicit conversion allows you to do thing when you know the conversion will work.

    public class MyClass
    {
        public animal MyAnimal { get; private set; }
    
        public MyClass ()
        {
            MyAnimal = new dog ();
        }
    
        public void SetAge (int Age)
        {
            ((dog)MyAnimal).age = Age;
        }
    }
    

    In this case, we know that MyAnimal is actually a dog, 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 animal will always contain the properties and methods of a dog.