E
E
ebroker2019-02-28 22:57:16
.NET
ebroker, 2019-02-28 22:57:16

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

3 answer(s)
A
Alexander Yudakov, 2019-02-28
@AlexanderYudakov

They say the cost is high.
https://switch-case.ru/73228064

E
eRKa, 2019-03-01
@kttotto

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.

J
John_Nash, 2019-03-01
@John_Nash

object o = new MyType();
var entity = (MyType)o;

this does not lead to a change in the object, which means that resources are not wasted
, maybe this will answer the question

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question