7.9. Implicit Argument ConversionsAn important feature of argument passing is implicit argument conversionconverting an argument's value to a type that the method expects to receive in its corresponding parameter. Visual Basic supports both widening and narrowing conversions. A widening conversion occurs when an argument is converted to a parameter of another type that can hold more data, whereas a narrowing conversion occurs when there is potential for data loss during the conversion (i.e., a conversion to a parameter of a type that holds a smaller amount of data). Figure 7.6 lists the widening conversions supported by Visual Basic that occur between primitive types. In addition to the conversions in Fig. 7.6, all primitive type variables can be converted to type Object without losing data.
For example, the Math class method Sqrt can be called with an Integer argument, even though the method is defined in class Math with a Double parameter. The statement Console.Write(Math.Sqrt(4)) correctly evaluates Math.Sqrt(4) and prints the value 2. Visual Basic implicitly converts the Integer argument 4 to the Double value 4.0 before the argument is passed to Math.Sqrt. In this case, the argument does not precisely correspond to the parameter type in the method declaration, so an implicit widening conversion changes the value to the proper type before the method is called. Visual Basic also performs narrowing conversions on arguments passed to methods. For example, if a Double variable containing the value 4.0 were passed to a method expecting an Integer variable, the value would be converted to 4. Some implicit narrowing conversions can cause runtime errors. In the next section, we discuss measures you can take to avoid such runtime errors. In Chapter 12, Exception Handling, we discuss how to handle the errors caused by failed narrowing conversions. Common Programming Error 7.8
Conversions occur not only for values passed as arguments to methods, but also for expressions containing values of two or more types. In such expressions, the values' original types are maintained, while temporary copies of the values are converted for use in the expression. Each value is converted to the "widest" type in the expression (i.e., widening conversions are made until the values are of the same type as the "widest" type). For example, if singleNumber is of type Single and integerNumber is of type Integer, when Visual Basic evaluates the expression singleNumber + integerNumber the value of integerNumber is converted to type Single (the widest type in the expression), then added to singleNumber, producing a Single result. |