Auto type conversion in VB.NET

By | January 12, 2018

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 compiler.

Become an Expert in Programming and Web Development.View all courses!

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

  • Widening Conversion
  • Narrowing conversion

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

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.

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.

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 automatically takes care of. Check in the below code:

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

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

I will discuss about this keyword in next article.