Answer the question
In order to leave comments, you need to log in
How is type casting done in C#?
How does the compiler cast reference types to each other under the hood? There is a base class A, B and C are inherited from it.
What is the difference between:
(B)A
A is B
A as B
I know that the first option is the most expensive, but why? And why is upcasting so much cheaper than downcasting?
Answer the question
In order to leave comments, you need to log in
Google what a Virtual Method Table is.
This is roughly how it works.
In short, using a class cast, you specify from which vtable to take the default methods, if this is very simplified.
Here is a good analysis:
https://www.msdr.ru/21/
When downcasting, you must first check whether the type can be cast to the desired one, and throw an exception if not.
Throwing exceptions is more expensive than just returning false or null, as is the case with is/as.
And the upcast is guaranteed to always pass, because it is cheaper than the downcast - JIT simply removes the code that is responsible for throwing exceptions.
Therefore, in the case of an upcast, as T and (T) gives the same result.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question