Type Conversions in VB.NET

In this article I will explain you about type conversion in VB.NET
  • 2591

Conversion allows you to treat one type as another. For example, storing an integer value in a long variable constitutes conversion from integer to a long. VB.NET supports limited implicit conversions as well as explicit conversions.
With implicit conversions, you pass a type to another type without losing any data.
The example below declares two variable, one of type double and the other integer. The double data type is assigned a value and is converted to integer type.

    Imports System.Console
    Module Module1
        Sub Main()
            Dim d=132.31223 as Double
            Dim i As Integer
            i = d
"Integer value is" & i)
        End Sub
Implicit conversion is only possible when you pass a small-range type to a big-range type. A long data type can hold short and integer values with no problem, but the reverse is not true without risking data loss.

In explicit conversions, you must cast a type with another type to pass data between them.
This conversion is also called as cast. Explicit conversions are accomplished using CType function. CType function for conversion. If we are not sure of the name of a particular conversion function then we can use the CType function. The above example with a CType function looks like this:

    Imports System.Console
    Module Module1
        Sub Main()
            Dim d As Double
            d = 132.31223
            Dim i As Integer
            i = CType(d, i)
            'two arguments, type we are converting from, to type desired
            WriteLine("Integer value is" & i)
        End Sub

The following table summarizes the widening conversions VB.Net will perform for us automatically.


Convert To

Byte Short,Integer,Long,Decimal,Single,Double
Short Integer,Long,Decimal,Single,Double
Integer Long,Decimal,Single,Double
Long Decimal,Single,Double
Decimal Single,Double
Single Double
Double none
Char Strin

Boxing and Unboxing

The term boxing describes the process of converting a value type into a reference type. The following conversion is an example of boxing, which is always an implicit conversion.

    Dim int1 As Integer = 34
    Dim obj As [Object] = int1

With the preceding example, you could output these variables:


The value of both int1 and obj is 34.

When unboxing (the reverse process of boxing), you convert a reference type to a value type, as in the following example.

    Dim obj As [Object] = 43
    Dim i As Integer = CInt(obj) 

From the example, you can output these variables:


Hope this article would have helped you in understanding conversion in VB.NET


More Articles

© 2020 DotNetHeaven. All rights reserved.