0
Downcast
Почему не получается сделать downcast и вылазит исключение ? Animal animal2 = new Animal(); animal2.Age = 20; Dog dog2 = (Dog)animal2; Console.WriteLine(dog2.Age);
1 Resposta
+ 2
animal2 was created as an instance of Animal. In this case it is impossible to downcast it to Dog, because the compiler knows that a subclass might have additional methods and fields compared to a parent class, that may not have been initialized. So this is illegal operation.
You can downcast only if you create your object as the instance of the subclass:
Animal animal2 = new Dog();
https://javabeat.net/java-downcasting/
https://stackoverflow.com/questions/380813/downcasting-in-java
https://stackoverflow.com/questions/16215143/how-do-i-turn-an-animal-instance-into-a-dog-instance
Actually I realized you ask about C# but I believe the rules and the syntax are the same.