Saturday, June 11, 2011

.NET interview questions :- What are stack , heap , value , reference types , boxing and unboxing ?

Stack and heap are memory types in an application. Stack memory stores data types like int , double , Boolean etc. While heap stores data types like string and objects.

For instance when the below code runs the first two variables i.e. “i” and “y” are stored in a stack and the last variable “o” is stored in heap.

void MyFunction()
int i = 1; // This is stored in stack.
int y = i; // This is stored in stack.
object o = null; // This is stored in heap.
} // after this end the stack variable memory space is reclaimed while //
the heap memory is reclaimed later by garbage collector.

Value types contain actual data while reference types contain pointers and the pointers point to the actual data.

Value types are stored on stack while reference types are stored on heap. Value types are are your normal data types like int , bool , double and reference types are all objects.

When value type is moved to a reference type it’s called as boxing. The vice-versa is termed as unboxing.

Attaching to the above one more c# interview which comes up is What is boxing and unboxing , below is the video which explains the same.

Please click here to see more Most asked c# interview questions

1 comment:

Dr. Rajesh Rolen said...

Thanks for good article.
Please provide some more details about stack and heap for Global Variables, Const Variables

Rajesh Rolen