Value and reference types in VB.NET

This blog defines Value and reference types  in VB.NET.

Value Type

A data type is a value type if it holds the data within its own memory allocation. Value types are stored directly on the stack. Value types can not contain the value null. We assign a value to that variable like this: x=11. When a variable of value type goes out of scope, it is destroyed and it's memory is reclaimed.

Value types include the following:
  • All numeric data types
  • Boolean, Char, and Date
  • All structures, even if their members are reference types
  • Enumerations, since their underlying type is always SByte, Short, Integer, Long, Byte, UShort, UInteger, or ULong

For example

The following code defines an int type variable. int type is a value type.

Module Module1

    Sub Main()

        Dim m As Integer = 5

        Dim n As Integer = m

        m = 3

        Console.WriteLine("m=" & m)

        Console.WriteLine("n=" & n)

    End Sub

End Module

 

OUTPUT


w1.gif

Reference Type

A reference type contains a pointer to another memory location that holds the data.while Reference types are stored on the run-time heap. Value types can contain the value null. Creating a variable of reference type is a two-step process, declare and instantiate. The first step is to declare a variable as that type. The second step, instantiation, creates the object.

Reference types include the following:
  • String
  • All arrays, even if their elements are value types
  • Class types, such as Form
  • Delegates

For Example

Module Module1

    Sub Main()

        Dim objX As New System.Text.StringBuilder(" Rohatash Kumasr")

        Dim objY As System.Text.StringBuilder

        objY = objX

        objX.Replace("World", "Test")

        Console.WriteLine(objY.ToString())

    End Sub

End Module

 

OUTPUT


w2.gif