Answer the question
In order to leave comments, you need to log in
C# type casting cost?
Interested in the question what happens inside the CLR during such an operation?
What is the cost of such operations?
Only reference types are of interest (boxing / unboxing is not considered). I did not find an answer in richter, which is strange.
object o = new MyType();
var entity = (MyType)o;
Answer the question
In order to leave comments, you need to log in
They say the cost is high.
https://switch-case.ru/73228064
For reference types, at runtime, it costs next to nothing. The main check for a ghost occurs at compile time.
In fact, with such a cast, there is no need to create a new object, move it in memory. Just the entity reference will now point to the MyType object, but the access to the interface will be different.
In runtime, you can crash with a ghost error if you put MyType1 in an object, and try to bring it to MyType2, the interfaces will not match and it is clear that there will be nothing to call.
PS: I looked it up with a search, it's all written in MSDN
The cast operation between reference types does not change the run-time type of the underlying object; only the type of the value that is used as a reference to that object changes.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question