Question

Ok imagine I have a base class BaseClass, as well as a child class ChildClassA which derives from BaseClass.

What happens when I do this?

BaseClass b = new ChildClassA;

What I imagine is happening is that:

  1. ChildClassA gets created and stored on the heap as a ChildClassA type!
  2. The variable b gets assigned a reference to the ChildClassA
  3. There is an implicit conversion from the ChildClassA to BaseClass
  4. But the object is still stored in the heap as a ChildClassA

The reason I ask is that as I understand it, once an object is declared and stored on the heap, that's what it ALWAYS is. A conversion just tells the CLR to treat it like it's a different type, but it really always still is the original type, and knows it's still the original type.

Am I correct? Anything I am missing here?

Was it helpful?

Solution

You're spot on with your understanding.

b refers to the ChildClassA instance. The latter is still on the heap as it was previously and no new objects are heapificated as a result of the assignment of the instance to BaseClass b.

OTHER TIPS

By Jove, you've got it!

A conversion just tells the CLR to treat it like it's a different type,

Actually it's not a conversion, more like an interpretation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top