Can you explain the difference between stack and heap memory?
sobes.tech AI
Answer from AI
Stack and heap are two different areas of memory used in C# for storing data, and they differ in management and purpose.
-
Stack is a memory area where local variables and method parameters are stored. It operates on a LIFO (last-in, first-out) principle. Memory in the stack is allocated and freed automatically when entering and exiting functions, which is very fast. The stack stores primitive type values and references to objects.
-
Heap is a memory area for dynamic allocation of objects. When an object is created using
new, memory is allocated on the heap. Memory management in the heap is handled by the garbage collector, which frees unused objects. The heap is more flexible, but allocation and deallocation operations are slower than in the stack.
Example:
void Example()
{
int x = 10; // x is stored in the stack
MyClass obj = new MyClass(); // obj is a reference in the stack, object is in the heap
}
Here, x is a local variable in the stack, and obj is a reference in the stack pointing to an object in the heap.