Downcast | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson


Почему не получается сделать downcast и вылазит исключение ? Animal animal2 = new Animal(); animal2.Age = 20; Dog dog2 = (Dog)animal2; Console.WriteLine(dog2.Age);

21st Aug 2020, 5:05 PM
Антон - avatar
1 Answer
+ 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(); Actually I realized you ask about C# but I believe the rules and the syntax are the same.
21st Aug 2020, 7:47 PM
Tibor Santa
Tibor Santa - avatar