How Reference and Value types are stored in memory ?

Introduction:

There are basically two types of variables in Common Type System ?

1) Value Type - Get Stored on Stack Memory.
2) Reference Type - Get Stored on Managed Heap Memory

How this Works?
Value types get stored on stack and shared the same process memory, however the Reference Types get stored on Heap and their memory address value gets stored on the stack as value type.

Question: When an object (child Object) is instantiated inside an object (parent Object) where does it get stored?
Answer: The value of child object (Reference type) gets stored in another random memory area on the managed heap and its reference (memory address value) gets stored in the managed heap of the Parent Object as Value Type.

The value of child object (Value type) gets stored in the Parent object's memory area of the managed heap.

For Example:

Module Module1 'Main Entry
Sub Main()
Dim i As Integer = 50
Dim objA As classA = New ClassA
Dim j As Integer = 25
End Sub
End Module

Public Class ClassA 'Parent Class
Dim obj As New ClassB
Dim MoreInfo As String = "sample"
End Class 

Public Class ClassB 'Child Class
Public name As String
Public age As Integer
End Class

As you can determine from the figure, that value of the ObjA gets stored in the Managed Heap and its memory address value gets stored on the Stack. But, in case of ObjB the value of the ObjB gets stored at another location in the Managed Heap and the memory address value of this location gets stored as a value type in ObjA Managed Heap.

Comments

  • Anonymous
    November 26, 2004
    well,that's pretty
  • Anonymous
    November 26, 2004
    Please change the color schema of your blog. Seriously, please! Great info, on the other hand.
  • Anonymous
    November 27, 2004
    The comment has been removed
  • Anonymous
    November 28, 2004
    Blog link of the week 48
  • Anonymous
    November 29, 2004
    The comment has been removed
  • Anonymous
    November 29, 2004
    Not as such, figure will be there soon. I apolize for the same.

  • Anonymous
    May 26, 2009
    PingBack from http://castironbakeware.info/story.php?title=saurabh-s-world-of-possibilities-how-reference-and-value-types