[SOLVED] <as> operator | Sololearn: Learn to code for FREE!

+6

[SOLVED] <as> operator

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

c#

9/14/2021 9:47:29 PM

Kiwwi#

8 Answers

New Answer

+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.

+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;

+3

then basically what I get is that <as> only works vertically in an inheritance hierarchy For true casting should use "direct casting".

+2

Tibor Santa then if cast it to a sibling type it wouldn't be the same, right?

+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.

+2

Tibor Santa then there's no way to cast to a sibling?

+1

Nope. :)

+1

tbh its hard to believe, anyways workarounds to emulate the behavior are possible (relative to results)