In order to understand stack and heap, let’s understand what actually happens in the below code internally.
It’s a three line code, let’s understand line by line how things execute internally.
Now many of our developer friends must be wondering why two types of
memory, can’t we just allocate everything on just one memory type and we
are done?
If you look closely, primitive data types are not complex, they hold single values like ‘
int i = 0
’.
Object data types are complex, they reference
other objects or other primitive data types. In other words, they hold
reference to other multiple values and each one of them must be stored
in memory.
Object types need dynamic memory while primitive ones needs static type
memory. If the requirement is of dynamic memory, it’s allocated on
the heap or else it goes on a stack.
Value types and reference types
Now that we have understood the concept of Stack and Heap, it’s time
to understand the concept of value types and reference types. Value
types are types which hold both data and memory on the same location.
A reference type has a pointer which points to the memory location.
IMAGE FOR VALUE TYPE EXAMPLE
|
Value Types Vs Reference Types Dotnet |
IMAGE FOR REFERENCE TYPE EXAMPLE
|
Value Types Vs Reference Types Dotnet |
Value Types
Value
types are primitive types that are mapped directly to the FCL. Like
Int32 maps to System.Int32, double maps to System.double. All value
types are stored on stack and all the value types are derived from
System.ValueType. All structures and enumerated types that are derived
from System.ValueType are created on stack, hence known as ValueType.
Reference Types
Reference
Types are different from value types in such a way that memory is
allocated to them from the heap. All the classes are of reference type.
C# new operator returns the memory address of the object.
Boxing and
unboxing is a essential concept in C#’s type system. With Boxing and
unboxing one can link between value-types and reference-types by
allowing any value of a value-type to be converted to and from type
object.