InternetUnicodeHTMLCSSScalable Vector Graphics (SVG)Extensible Markup Language (xml) ASP.Net TOCASP.NetMiscellaneous Feature ASP.NET Scripting Visual Basic .NET TOCVB .NET Language Referencena VB.Net Keywords Draft for Information Only
Content
VB.NET Conversions of Data
VB.NET Conversions of DataType Conversions in Visual BasicThe process of changing a value from one data type to another type is called conversion. Conversions are either widening or narrowing, depending on the data capacities of the types involved. They are also implicit or explicit, depending on the syntax in the source code. Related Sections
Data Types
Data Types
Troubleshooting Data Types Widening and Narrowing ConversionsAn important consideration with a type conversion is whether the result of the conversion is within the range of the destination data type. A widening conversion changes a value to a data type that can allow for any possible value of the original data. Widening conversions preserve the source value but can change its representation. This occurs if you convert from an integral type to Decimal, or from Char to String. A narrowing conversion changes a value to a data type that might not be able to hold some of the possible values. For example, a fractional value is rounded when it is converted to an integral type, and a numeric type being converted to Boolean is reduced to either True or False. Widening ConversionsThe following table shows the standard widening conversions.
1 By definition, every data type widens to itself. 2 Conversions from Integer, UInteger, Long, ULong, or Decimal to Single or Double might result in loss of precision, but never in loss of magnitude. In this sense they do not incur information loss. 3 It might seem surprising that a conversion from a derived type to one of its base types is widening. The justification is that the derived type contains all the members of the base type, so it qualifies as an instance of the base type. In the opposite direction, the base type does not contain any new members defined by the derived type. Widening conversions always succeed at run time and never incur data loss. You can always perform them implicitly, whether the Option Strict Statement sets the type checking switch to On or to Off. Narrowing ConversionsThe standard narrowing conversions include the following:
Narrowing conversions do not always succeed at run time, and can fail or incur data loss. An error occurs if the destination data type cannot receive the value being converted. For example, a numeric conversion can result in an overflow. The compiler does not allow you to perform narrowing conversions implicitly unless the Option Strict Statement sets the type checking switch to Off. Note The narrowing-conversion error is suppressed for conversions from the elements in a For Each…Next collection to the loop control variable. For more information and examples, see the "Narrowing Conversions" section in For Each...Next Statement. When to Use Narrowing ConversionsYou use a narrowing conversion when you know the source value can be converted to the destination data type without error or data loss. For example, if you have a String that you know contains either "True" or "False," you can use the CBool keyword to convert it to Boolean. Exceptions During ConversionBecause widening conversions always succeed, they do not throw exceptions. Narrowing conversions, when they fail, most commonly throw the following exceptions:
If a class or structure defines a CType Function to serve as a conversion operator to or from that class or structure, that CType can throw any exception it deems appropriate. In addition, that CType might call Visual Basic functions or .NET Framework methods, which in turn could throw a variety of exceptions. Changes During Reference Type ConversionsA conversion from a reference type copies only the pointer to the value. The value itself is neither copied nor changed in any way. The only thing that can change is the data type of the variable holding the pointer. In the following example, the data type is converted from the derived class to its base class, but the object that both variables now point to is unchanged. ' Assume class cSquare inherits from class cShape. Dim shape As cShape Dim square As cSquare = New cSquare ' The following statement performs a widening ' conversion from a derived class to its base class. shape = square See also
Implicit and Explicit ConversionsAn implicit conversion does not require any special syntax in the source code. In the following example, Visual Basic implicitly converts the value of k to a single-precision floating-point value before assigning it to q. VBDim k As Integer Dim q As Double ' Integer widens to Double, so you can do this with Option Strict On. k = 432 q = k An explicit conversion uses a type conversion keyword. Visual Basic provides several such keywords, which coerce an expression in parentheses to the desired data type. These keywords act like functions, but the compiler generates the code inline, so execution is slightly faster than with a function call. In the following extension of the preceding example, the CInt keyword converts the value of q back to an integer before assigning it to k. VB' q had been assigned the value 432 from k. q = Math.Sqrt(q) k = CInt(q) ' k now has the value 21 (rounded square root of 432). Conversion KeywordsThe following table shows the available conversion keywords.
The CType FunctionThe CType Function operates on two arguments. The first is the expression to be converted, and the second is the destination data type or object class. Note that the first argument must be an expression, not a type. CType is an inline function, meaning the compiled code makes the conversion, often without generating a function call. This improves performance. For a comparison of CType with the other type conversion keywords, see DirectCast Operator and TryCast Operator. Elementary TypesThe following example demonstrates the use of CType. VBk = CType(q, Integer) ' The following statement coerces w to the specific object class Label. f = CType(w, Label) Composite TypesYou can use CType to convert values to composite data types as well as to elementary types. You can also use it to coerce an object class to the type of one of its interfaces, as in the following example. VB' Assume class cZone implements interface iZone. Dim h As Object ' The first argument to CType must be an expression, not a type. Dim cZ As cZone ' The following statement coerces a cZone object to its interface iZone. h = CType(cZ, iZone) Array TypesCType can also convert array data types, as in the following example. VBDim v() As classV Dim obArray() As Object ' Assume some object array has been assigned to obArray. ' Check for run-time type compatibility. If TypeOf obArray Is classV() ' obArray can be converted to classV. v = CType(obArray, classV()) End If For more information and an example, see Array Conversions. Types Defining CTypeYou can define CType on a class or structure you have defined. This allows you to convert values to and from the type of your class or structure. For more information and an example, see How to: Define a Conversion Operator. Note Values used with a conversion keyword must be valid for the destination data type, or an error occurs. For example, if you attempt to convert a Long to an Integer, the value of the Long must be within the valid range for the Integer data type. Caution Specifying CType to convert from one class type to another fails at run time if the source type does not derive from the destination type. Such a failure throws an InvalidCastException exception. However, if one of the types is a structure or class you have defined, and if you have defined CType on that structure or class, a conversion can succeed if it satisfies the requirements of your CType. See How to: Define a Conversion Operator. Performing an explicit conversion is also known as casting an expression to a given data type or object class. See also
Conversions Between Strings and Other TypesYou can convert a numeric, Boolean, or date/time value to a String. You can also convert in the reverse direction — from a string value to numeric, Boolean, or Date — provided the contents of the string can be interpreted as a valid value of the destination data type. If they cannot, a run-time error occurs. The conversions for all these assignments, in either direction, are narrowing conversions. You should use the type conversion keywords (CBool, CByte, CDate, CDbl, CDec, CInt, CLng, CSByte, CShort, CSng, CStr, CUInt, CULng, CUShort, and CType). The Format and Val functions give you additional control over conversions between strings and numbers. If you have defined a class or structure, you can define type conversion operators between String and the type of your class or structure. For more information, see How to: Define a Conversion Operator. Conversion of Numbers to StringsYou can use the Format function to convert a number to a formatted string, which can include not only the appropriate digits but also formatting symbols such as a currency sign (such as $), thousands separators or digit grouping symbols (such as ,), and a decimal separator (such as .). Format automatically uses the appropriate symbols according to the Regional Options settings specified in the Windows Control Panel. Note that the concatenation (&) operator can convert a number to a string implicitly, as the following example shows. ' The following statement converts count to a String value. Str = "The total count is " & count Conversion of Strings to NumbersYou can use the Val function to explicitly convert the digits in a string to a number. Val reads the string until it encounters a character other than a digit, space, tab, line feed, or period. The sequences "&O" and "&H" alter the base of the number system and terminate the scanning. Until it stops reading, Val converts all appropriate characters to a numeric value. For example, the following statement returns the value 141.825. Val(" 14 1.825 miles") When Visual Basic converts a string to a numeric value, it uses the Regional Options settings specified in the Windows Control Panel to interpret the thousands separator, decimal separator, and currency symbol. This means that a conversion might succeed under one setting but not another. For example, "$14.20" is acceptable in the English (United States) locale but not in any French locale. See also
How to: Convert an Object to Another Type in Visual BasicYou convert an Object variable to another data type by using a conversion keyword such as CType Function. ExampleThe following example converts an Object variable to an Integer and a String. Public Sub objectConversion(ByVal anObject As Object) Dim anInteger As Integer Dim aString As String anInteger = CType(anObject, Integer) aString = CType(anObject, String) End Sub If you know that the contents of an Object variable are of a particular data type, it is better to convert the variable to that data type. If you continue to use the Object variable, you incur either boxing and unboxing (for a value type) or late binding (for a reference type). These operations all take extra execution time and make your performance slower. Compiling the CodeThis example requires:
See also
Array ConversionsYou can convert an array type to a different array type provided you meet the following conditions:
A conversion of one array type to another is widening or narrowing depending on whether the conversion of the respective elements is widening or narrowing. For more information, see Widening and Narrowing Conversions. Conversion to an Object ArrayWhen you declare an Object array without initializing it, its element type is Object as long as it remains uninitialized. When you set it to an array of a specific class, it takes on the type of that class. However, its underlying type is still Object, and you can subsequently set it to another array of an unrelated class. Since all classes derive from Object, you can change the array's element type from any class to any other class. In the following example, no conversion exists between types student and String, but both derive from Object, so all assignments are valid. ' Assume student has already been defined as a class. Dim testArray() As Object ' testArray is still an Object array at this point. Dim names() As String = New String(3) {"Name0", "Name1", "Name2", "Name3"} testArray = New student(3) {} ' testArray is now of type student(). testArray = names ' testArray is now a String array. Underlying Type of an ArrayIf you originally declare an array with a specific class, its underlying element type is that class. If you subsequently set it to an array of another class, there must be a conversion between the two classes. In the following example, students is a student array. Since no conversion exists between String and student, the last statement fails. Dim students() As student Dim names() As String = New String(3) {"Name0", "Name1", "Name2", "Name3"} students = New Student(3) {} ' The following statement fails at compile time. students = names See also
Source/Reference
©sideway ID: 200900022 Last Updated: 9/22/2020 Revision: 0 Ref: References
Latest Updated Links
|
Home 5 Business Management HBR 3 Information Recreation Hobbies 8 Culture Chinese 1097 English 339 Travel 7 Reference 79 Computer Hardware 251 Software Application 213 Digitization 32 Latex 52 Manim 205 KB 1 Numeric 19 Programming Web 289 Unicode 504 HTML 66 CSS 65 SVG 46 ASP.NET 270 OS 431 DeskTop 7 Python 72 Knowledge Mathematics Formulas 8 Set 1 Logic 1 Algebra 84 Number Theory 206 Trigonometry 31 Geometry 34 Calculus 67 Engineering Tables 8 Mechanical Rigid Bodies Statics 92 Dynamics 37 Fluid 5 Control Acoustics 19 Natural Sciences Matter 1 Electric 27 Biology 1 |
Copyright © 2000-2024 Sideway . All rights reserved Disclaimers last modified on 06 September 2019