Dot Net For All

Auto type conversion in VB.NET

Type conversion is an important aspect of any programming language. Type conversion happen when we try to assign value of one type to value of another type. These are the types of conversion which are automatically done by vb.net compiler.

There are basically two type of conversions in .NET. And they are

In widening conversion there are chances of data loss, while in narrowing conversion there is no chance of data loss.

Lets see each of them with example in the below code.

In the below code I have declared five type of variables

        Dim x As Integer = 9
        Dim y As Double = 3.18
        Dim s1 As String = "12.5"
        Dim s2 As String = "FOO"
        Dim d As Date = #05/01/2018#

Now lets assign x to y. This is the type of conversion where there would be no data loss. Here every value that an integer represents can be represented by double as well. Lets see it in action in the below code.

        y = x
        Console.WriteLine(string.Format("Output: {0}", y)) 'Output: 9

In another case assign y to x. This is the type of conversion where there are very good chances of data loss as double cannot be represented by integer. See in the below code.

        x = y
        Console.WriteLine(string.Format("Output: {0}", x)) 'Output: 3
        Console.Read()

We get the result as only 3. This is the narrowing conversion.

Same thing happens for expression also. If I add x and y, and assign it to y there would not be any data loss.

But is I assign addition of x and y to x, there would be data loss.

There are other type of conversion which vb.net automatically takes care of. Check in the below code:

        y = y + s1
        Console.WriteLine(string.Format("Output: {0}", y)) 'Output: 15.68

If we add a double and string, and assign it to a double we will get the result as double. Because the vb.net converts the string into a double and does the addition.

Though it is a very good programming help provided by vb.net but it can have some devastating effects. To prevent from unsafe conversion vb.net provide Option On Strict keyword which can be used to prevent narrowing conversion.

I will discuss about this keyword in next article.

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview