Click here to Skip to main content
15,898,222 members
Please Sign up or sign in to vote.
4.33/5 (3 votes)
See more:
Can anyone explain me the behaviour of Stack and Heap when an object(Integer) is type casted as a data type(int)?

Any thoughtful ideas would be welcome..


Regards
Rajeev


P.S. Am posting it here, as it is a scenario-based query. Honestly,I didn't google for this one , as I was aware that this is a CP - level question.
Posted
Comments
Sergey Alexandrovich Kryukov 25-Mar-11 20:13pm    
Pretty good question, not very trivial (which is very rate here: 99.9% of other questions are either gravely incorrect (most usual case) or trivial (less often)). I vote 4. (I would vote 5 is boxing and unboxing terminology was used :-)
--SA
rajivpande86 28-Mar-11 16:20pm    
:) Came to know your trick of voting..
Sergey Alexandrovich Kryukov 28-Mar-11 19:12pm    
Why do you call my vote a trick?
And are you accepting my Answer or not?
--SA

1 solution

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
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900