This blog defines the boxing and unboxing in VB.NET.

Boxing and Unboxing in VB.NET

Visual Basic provides us with Value types and Reference Types. Value Types are stored on the stack and Reference types are stored on the heap.

Boxing

The conversion of value type to reference type is known as Boxing.

The below code defines the Boxing the i to object.

C# code

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ConsoleApplication36

{

class Program

{

static void Main(string[] args)

{

int i = 0;

object obj = i;

Console.WriteLine(obj);

}

}

}

VB code

Module Module1

Sub Main()

Dim i As Integer = 0

Dim obj As Object = i

Console.WriteLine(obj)

End Sub

End Module

Unboxing

The conversion of reference type back to the value type is known as Unboxing.

The below code defines the Unboxing.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ConsoleApplication39

{

class Program

{

static void Main(string[] args)

{

int i = 0;

object obj = i;

int j = (int)obj;

Console.WriteLine(obj);

Console.WriteLine(j);

}

}

}

VB code

Module Module1

Sub Main()

Dim i As Integer = 0

Dim obj As Object = i

Dim j As Integer = CInt(obj)

Console.WriteLine(obj)

Console.WriteLine(j)

End Sub

End Module