Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 772
paul sim Avatar asked Dec 16 '11 03:12

paul sim


2 Answers

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

like image 94
Marty Avatar answered Oct 21 '22 01:10

Marty


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.

like image 30
Jim D'Angelo Avatar answered Oct 21 '22 00:10

Jim D'Angelo