Day 21 : Stack and Heap in C#

 

Value Type and Reference Type :

                             Value types and Reference type are the types of data type which are divided on basis of how they store their values in memory.

Value Type :

  • A data type is said to be value type if it holds a data value in its own memory.
  • Variables of these data type directly contains values.
  • The data types which are value type are : bool, byte, int, char, float, enum, short, long, struct,decimal, double etc.
  • If a variable is passed by value type then the system creates another copy for that variable.
  • Because of this if value got changed for one variable it won't affect another.
  • It uses stack for storing data.



Reference Type :

  • Reference type doesn't store it's value directly.
  • It stores the address(stack) where the value(heap) is being stored.
  • A reference type contains pointer which points to another memory location where the data is stored.
  • It uses stack as well as heap for storing data.
  • The data types which are reference type are : Array, Class, String etc.
  • When a variable is passed by reference type, it doesn't create another copy like value type.
  • As it passes variable address, when we change one value the second also get changed as they point on one location. 



String is a reference type but immutable. Means once we assigned a value, it won't be changed later. If we change string value, compiler creates new object in memory and point variable to new location. So it won't change the original value.


Stack and Heap :

Stack :

  • The stack is LIFO(Last-In-First-Out) data structure where the data can be added and deleted from top of the stack.
  • Stack is a linear data structure having contiguous block.
  • Declaration of variables in stack are of value-type.
  • Stack allows us to access local variables only.
  • The allocation of memory is static.
  • The access time is more compared to heap.
  • The memory deallocation is done when method completes it's execution.

Heap :

  • The heap is a area of  memory where data can be added and deleted in any order
  • Heap is a hierarchical data structure having random order.
  • Declaration of variables in heap are of reference-type.
  • Heap allows us to access global variables.
  • The allocation of memory is dynamic.
  • The access time is less compared to stack.
  • The memory deallocation is done by user using garbage collector.
The structure of stack and heap for above example is :




Thank You!!!

For more understanding watch below video :



Comments

Popular posts from this blog

Day 3 : JavaScript

SQL Concepts-1

ASP .NET Session Management