+ 6

[SOLVED] <as> operator

Why it shows "Derived"? It should be "Base" isn't it? https://code.sololearn.com/cOO5xvUzYOOs/?ref=app

14th Sep 2021, 9:47 PM
Kiwwi#
Kiwwi# - avatar
8 Respuestas
+ 2
Casting to sibling type won't work, only in very exceptional cases (like casting between different numeric types, and even then with limitations / potential runtime errors). Normally you can only cast along the type hierarchy.
15th Sep 2021, 5:17 AM
Tibor Santa
Tibor Santa - avatar
+ 3
You should put a little research into runtime polymorphism, it is a very important OOP concept. https://stackoverflow.com/questions/23072198/polymorphism-and-casting#23072229 "Casting does not change run-time type of object" Your obj2 is still a Derived type in the background, but because of the typecast, now it acts like its base class. But you can also convert it back to Derived at any time, without losing data. Derived obj3 = obj2 as Derived;
15th Sep 2021, 4:39 AM
Tibor Santa
Tibor Santa - avatar
+ 3
then basically what I get is that <as> only works vertically in an inheritance hierarchy For true casting should use "direct casting".
15th Sep 2021, 3:47 PM
Kiwwi#
Kiwwi# - avatar
+ 2
Tibor Santa then if cast it to a sibling type it wouldn't be the same, right?
15th Sep 2021, 4:58 AM
Kiwwi#
Kiwwi# - avatar
+ 2
Kiwwi# the same is true for direct casting, that it only works up/down the inheritance chain. The 'as' operator has the added benefit, that if you attempt to cast to an incompatible type, the result will be null instead of a runtime error.
15th Sep 2021, 5:14 PM
Tibor Santa
Tibor Santa - avatar
+ 2
Tibor Santa then there's no way to cast to a sibling?
15th Sep 2021, 5:44 PM
Kiwwi#
Kiwwi# - avatar
+ 1
Nope. :)
15th Sep 2021, 6:09 PM
Tibor Santa
Tibor Santa - avatar
+ 1
tbh its hard to believe, anyways workarounds to emulate the behavior are possible (relative to results)
15th Sep 2021, 6:29 PM
Kiwwi#
Kiwwi# - avatar