First, this is not exactly type casting, even though those concepts are related. This is called boxing and unboxing, see
http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx[
^].
What is called type casting in .NET is interpreting of one type as it was some another type. As no data is moved anywhere, it has nothing to do with stack or heap. As to stack, nothing happens to the stack pointer at all until stack frame is changed. This "normal" type casting in .NET is somewhat similar to C++ "reinterpret cast".
At to boxing in C#, stack allocation takes place, as some memory is need to hold an instance of
System.Object
descendant, such
as System.Int32
. Nothing happens on unboxing. Heap memory is eventually reclaimed by the Garbage Collector. First, the object should become inaccessible by any other accessible object in the
Application Domain. GC collects memory of the inaccessible object later, depending on GC behavior.
—SA