From the course: Visual Basic Essential Training

How data conversion works

- [Instructor] The process of changing a value from one data type to another type is called conversion. In this video, we'll look at conversion concepts for the Visual Basic built-in numeric types. To review, a variable is typed at declaration time. Once the variable is defined, it's type cannot be changed, and the variable can only store values that match its specified type. For this discussion, we will focus on the simpler numeric types and set aside topics related to class inheritance. To be clear, converting derived types to base classes and base classes to derive types is an important topic. It's not the topic for this chapter. It's the same for strings. They have their own idiosyncrasies. We'll look at how to convert to or from a string in the next chapter. In this code example: on line 49, we have a counter variable that is explicitly declared to hold integer values; on line 51, assigning an integer literal is acceptable because it matches the variables defined type; on line 52, we attempt to assign a double floating point literal. Since the variable cannot contain a double, there must be a conversion to an integer. The red squiggle is there because I've configured Visual Studio to warn me about implicit conversions. More details about this soon. On line 53, we resolve this by using the Convert class to explicitly convert from a double to an integer. This will work. The compiler is happy and there is no data loss. Line 55 shows a similar situation. However, in this case, the conversion will truncate the decimal portion of the number. This means that only the whole number part of the value will be retained, potentially leading to data loss. On line 56 and 57, we attempt to assign string values to the integer variable, which is not directly possible since an integer cannot hold a string. This requires a conversion. Therefore, the question is whether the strings can be successfully converted to an integer. Line 56 looks possible and will likely succeed. But not line 57. The string value hello cannot be meaningfully converted to an integer. This is an inappropriate assignment because the content of the string does not represent a number. Attempting such a conversion will likely result in a runtime error. When discussing conversions, it's important to understand the concepts of widening and narrowing conversions. As these determine how easily and safely one type can be converted to another type, essentially what matters is whether the value being converted can fit into the destination data type without loss or error. This depends on the range, precision, and compatibility of the source and destination types. A widening conversion occurs when a value of one data type is converted to a data type that can accommodate all possible values of the original type without loss of data or risk of failure. These conversions are safe and occur automatically in Visual Basic without requiring explicit code. Going in the other direction though is another story. A narrowing conversion occurs when a value is converted to a data type that has a smaller range or less precision, or where not all values of the original type can be represented in the target type. Here's an example of both widening and narrowing. Line 64 creates a Byte variable, which can store values from zero to 255. Line 67 creates a Short variable, which can store a larger range of values from negative 32768 up to 32767. Line 69 shows a widening conversion where the byte data is guaranteed to fit into the short variable. Line 71 shows a narrowing conversion. 600 will not fit in the byte, therefore, this conversion will cause a runtime exception. For other data types, it might cause rounding or truncation issues. Widening occurs when moving from small size variables to larger. So in this example, we can go from a byte to a short or a byte to integer, or a byte to a long. Essentially, anything on the left side can be widened to the items on the right side. Same with the singles, doubles, and decimals. Generally, you can also widen from scalar values to floating point values. So I can go from a short to a double. Narrowing goes the opposite direction from the widening list. When talking about conversions, the other essential concept to understand is the difference between implicit and explicit conversions. And implicit conversion does not require any special syntax in the source code. It just occurs automatically. This is usually the case for widening conversions. An explicit conversion uses a type conversion keyword or a converter class. In other words, you write code to indicate how to convert from one type to another. This is usually required for narrowing conversions. Visual Basic provides two sets of conversion tools. First is the older set of conversion keywords migrated from the old Visual Basic classic era. The older set of conversion functions are called the built-in conversion functions. They all start with the letter C for convert and then end with the target data type. So you have CInt for integers and CDbl for doubles, and so on. The newer conversion tools are contained in a .NET specific converter implemented as convert class methods. There is a method for each destination type. So you'll find methods named ToBool, ToInt32, ToDouble, and so on. In general, you'll get more precise error messages by using the convert class methods and they're generally recommended over the older built in conversion functions. By default, Visual Basic allows some implicit narrowing conversions. In this example, the VB Editor and the VB Compiler allow the implicit narrowing from short to byte. Line 72 will run successfully. Line 75 will throw a runtime exception, however. This behavior is different from many other programming languages. In Java, for example, if you start with a byte which has a maximum value of 255 and you add one, instead of getting 256, it will wrap around and become zero. In Visual Basic, that operation causes a runtime exception. You can configure a Visual Basic and Visual Studio to warn you when you're doing implicit narrowing with the option strict statement. By default, this is set to off for all Visual Basic code files, but it can be enabled at the file level or at the project level. Here are two examples of narrowing. One with option strict off and one with option strict on. Notice on the option, strict on version that I'm getting a red squiggle that is telling me that there's a potential issue with this conversion. With option strict on, you cannot compile the project unless you explicitly convert the short value. So that's a look at various ways of doing numeric conversions. Time for a few practical examples in Visual Studio.

Contents