How to use CASTING in VB.NET

This article shows how casting is done in Visual Basic.
  • 2104
Casting refers to the process of converting an expression form one data type to another. In many cases, though, Visual Basic does casting automatically.

Widening Conversions

Byte -> Short -> Integer -> Long -> Decimal -> Single -> Double
A widening conversion is one that casts data from a data type with a narrower range of possible values to a data type with  a wider range of possible values. Visual basic uses implicit casts to do widening conversions automatically. When you code an arithmetic expression, Visual Basic does widening conversions implicitly so all operands have the widest data type used in the expression.
 

Implicit Casts for widening conversions

Module Module1
    Sub Main()
        Dim grade As Double = 93
        Dim a As Double = 6.5
        Dim b As Integer = 6
        Dim c As Integer = 10
        Dim average As Double = (a + b + c) / 3
        Console.Write("grade = ")
        Console.WriteLine(grade)
        Console.Write("average = ")
        Console.Write(average)
        Console.ReadLine()
    End Sub
End Module

OUTPUT:

cas.gif

A narrowing conversions is one that casts data from a wider data type to a narrow data type.


Implicit casts for narrowing conversions

Module Module1
    Sub Main()
        Dim grade As Integer = 93.75
        Dim a As Double = 6.5
        Dim b As Integer = 6
        Dim c As Integer = 10
        Dim average As Integer = (a + b + c) / 3
        Console.Write("grade = ")
        Console.WriteLine(grade)
        Console.Write("average = ")
        Console.Write(average)
        Console.ReadLine()
    End Sub
End Module
 

OUTPUT:
cas2.gif

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.