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()
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
}