Thursday 26 November 2015

Boxing And Unboxing In VB.NET

Boxing is simply the process of converting a value type to any interface type implemented by the current value type; the most common being the Value object. Boxing is used to store value types in the garbage-collected heap.
This means that, once a variable is boxed, it can hold a separate value in a separate memory location. When a value type is boxed, a new object must be allocated and constructed.
Boxing and unboxing is an important concept in VB.NET'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.

Boxing
  • Boxing is a mechanism in which value type is converted into reference type.
  • It is implicit conversion process in which object type (super type) is used.
  • In this process type and value both are stored in object type
Unboxing
  • Unboxing is a mechanism in which reference type is converted into value.
  • It is explicit conversion process.

Program to show Boxing and Unboxing:

Module
 Module1
    
Sub Main()
        
Dim i As Integer = 10
        
Dim j As Integer
        ' boxing
        Dim o As Object
        o = i
        
'unboxing
        j = CInt(o)
        Console.WriteLine(
"value of o object : " & o)
        Console.WriteLine(
"Value of j : " & j)
        Console.ReadLine()
    
End Sub
End
 Module

Output of above program:




Conclusion:

Hope the article might have helped you in understanding Boxing and Unboxing. 

No comments:

Post a Comment