Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is data lost in down casting?

From what I know explicit casting is required when data is lost in the conversion process:

In the following, the casting operator () is required because the fractional portion (data) is lost in the conversion process: (int)6.88

However, in regards to downcasting, because the casting operator () is required to perform downcasting… is data lost? If so, what kind of data is lost? (Dog)new Animal()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class Animal
{
    // some code
}


public class Dog : Animal
{
    //some code
}

>Solution :

In case of class (reference type) you manipulate with reference and reference is still the same when you cast:

   // reference created 
   Dog dog = new Dog(); 

   // Reference is still the same, by you see it as Animal
   Animal animal = (Animal) dog;

   // Cast back to dog. The reference doesn't change, now you see it as Dog
   Dog myDog = (Dog) animal;

Note, that creating Animal (base class) and casting to Dog (derived class) is an error:

  Animal animal = new Animal();

  //  Here Animal can't be cast to Dog  
  Dog dog = (Dog) animal;

And you’ll have run time error:

System.InvalidCastException: ‘Unable to cast object of type ‘Animal’ to type ‘Dog’.’

When casting to derived type you can use pattern matching:

 if (animal is Dog myDog) {
   // reference animal can be cast to Dog - myDog
 }
 else {
   // cast is impossible
 }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading