Sideway
output.to from Sideway
Draft for Information Only

Content

VB.NET Conversions of Data
  Type Conversions in Visual Basic
 Related Sections
  Widening and Narrowing Conversions
 Widening Conversions
 Narrowing Conversions
  When to Use Narrowing Conversions
 Exceptions During Conversion
 Changes During Reference Type Conversions
 See also
  Implicit and Explicit Conversions
 Conversion Keywords
 The CType Function
  Elementary Types
  Composite Types
  Array Types
  Types Defining CType
 See also
  Conversions Between Strings and Other Types
 Conversion of Numbers to Strings
 Conversion of Strings to Numbers
 See also
  How to: Convert an Object to Another Type in Visual Basic
 Example
 Compiling the Code
 See also
  Array Conversions
 Conversion to an Object Array
  Underlying Type of an Array
 See also
  Source/Reference

VB.NET Conversions of Data

Type Conversions in Visual Basic

The 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
Introduces the Visual Basic data types and describes how to use them.

Data Types
Lists the elementary data types supplied by Visual Basic.

Troubleshooting Data Types
Discusses some common problems that can arise when working with data types.

Widening and Narrowing Conversions

An 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 Conversions

The following table shows the standard widening conversions.

Data type Widens to data types 1
SByte SByte, Short, Integer, Long, Decimal, Single, Double
Byte Byte, Short, UShort, Integer, UInteger, Long, ULong, Decimal, Single, Double
Short Short, Integer, Long, Decimal, Single, Double
UShort UShort, Integer, UInteger, Long, ULong, Decimal, Single, Double
Integer Integer, Long, Decimal, Single, Double2
UInteger UInteger, Long, ULong, Decimal, Single, Double2
Long Long, Decimal, Single, Double2
ULong ULong, Decimal, Single, Double2
Decimal Decimal, Single, Double2
Single Single, Double
Double Double
Any enumerated type (Enum) Its underlying integral type and any type to which the underlying type widens.
Char Char, String
Char array Char array, String
Any type Object
Any derived type Any base type from which it is derived 3.
Any type Any interface it implements.
Nothing Any data type or object type.

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 Conversions

The standard narrowing conversions include the following:

  • The reverse directions of the widening conversions in the preceding table (except that every type widens to itself)

  • Conversions in either direction between Boolean and any numeric type

  • Conversions from any numeric type to any enumerated type (Enum)

  • Conversions in either direction between String and any numeric type, Boolean, or Date

  • Conversions from a data type or object type to a type derived from it

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 Conversions

You 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 Conversion

Because 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 Conversions

A 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 Conversions

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

VB
Dim 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 Keywords

The following table shows the available conversion keywords.

Type conversion keyword Converts an expression to data type Allowable data types of expression to be converted
CBool Boolean Data Type Any numeric type (including Byte, SByte, and enumerated types), String, Object
CByte Byte Data Type Any numeric type (including SByte and enumerated types), Boolean, String, Object
CChar Char Data Type String, Object
CDate Date Data Type String, Object
CDbl Double Data Type Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object
CDec Decimal Data Type Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object
CInt Integer Data Type Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object
CLng Long Data Type Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object
CObj Object Data Type Any type
CSByte SByte Data Type Any numeric type (including Byte and enumerated types), Boolean, String, Object
CShort Short Data Type Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object
CSng Single Data Type Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object
CStr String Data Type Any numeric type (including Byte, SByte, and enumerated types), Boolean, Char, Char array, Date, Object
CType Type specified following the comma (,) When converting to an elementary data type (including an array of an elementary type), the same types as allowed for the corresponding conversion keyword

When converting to a composite data type, the interfaces it implements and the classes from which it inherits

When converting to a class or structure on which you have overloaded CType, that class or structure
CUInt UInteger Data Type Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object
CULng ULong Data Type Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object
CUShort UShort Data Type Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object

The CType Function

The 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 Types

The following example demonstrates the use of CType.

VB
k = CType(q, Integer)
' The following statement coerces w to the specific object class Label.
f = CType(w, Label)

Composite Types

You 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 Types

CType can also convert array data types, as in the following example.

VB
Dim 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 CType

You 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 Types

You 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 Strings

You 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 Numbers

You 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 Basic

You convert an Object variable to another data type by using a conversion keyword such as CType Function.

Example

The 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 Code

This example requires:

  • A reference to the System namespace.

See also

Array Conversions

You can convert an array type to a different array type provided you meet the following conditions:

  • Equal Rank. The ranks of the two arrays must be the same, that is, they must have the same number of dimensions. However, the lengths of the respective dimensions do not need to be the same.

  • Element Data Type. The data types of the elements of both arrays must be reference types. You cannot convert an Integer array to a Long array, or even to an Object array, because at least one value type is involved. For more information, see Value Types and Reference Types.

  • Convertibility. A conversion, either widening or narrowing, must be possible between the element types of the two arrays. An example that fails this requirement is an attempted conversion between a String array and an array of a class derived from System.Attribute. These two types have nothing in common, and no conversion of any kind exists between them.

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 Array

When 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 Array

If 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: 22/9/2020 Revision: 0 Ref:

close

References

  1. Active Server Pages,  , http://msdn.microsoft.com/en-us/library/aa286483.aspx
  2. ASP Overview,  , http://msdn.microsoft.com/en-us/library/ms524929%28v=vs.90%29.aspx
  3. ASP Best Practices,  , http://technet.microsoft.com/en-us/library/cc939157.aspx
  4. ASP Built-in Objects,  , http://msdn.microsoft.com/en-us/library/ie/ms524716(v=vs.90).aspx
  5. Response Object,  , http://msdn.microsoft.com/en-us/library/ms525405(v=vs.90).aspx
  6. Request Object,  , http://msdn.microsoft.com/en-us/library/ms524948(v=vs.90).aspx
  7. Server Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525541(v=vs.90).aspx
  8. Application Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525360(v=vs.90).aspx
  9. Session Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms524319(8v=vs.90).aspx
  10. ASPError Object,  , http://msdn.microsoft.com/en-us/library/ms524942(v=vs.90).aspx
  11. ObjectContext Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525667(v=vs.90).aspx
  12. Debugging Global.asa Files,  , http://msdn.microsoft.com/en-us/library/aa291249(v=vs.71).aspx
  13. How to: Debug Global.asa files,  , http://msdn.microsoft.com/en-us/library/ms241868(v=vs.80).aspx
  14. Calling COM Components from ASP Pages,  , http://msdn.microsoft.com/en-us/library/ms524620(v=VS.90).aspx
  15. IIS ASP Scripting Reference,  , http://msdn.microsoft.com/en-us/library/ms524664(v=vs.90).aspx
  16. ASP Keywords,  , http://msdn.microsoft.com/en-us/library/ms524672(v=vs.90).aspx
  17. Creating Simple ASP Pages,  , http://msdn.microsoft.com/en-us/library/ms524741(v=vs.90).aspx
  18. Including Files in ASP Applications,  , http://msdn.microsoft.com/en-us/library/ms524876(v=vs.90).aspx
  19. ASP Overview,  , http://msdn.microsoft.com/en-us/library/ms524929(v=vs.90).aspx
  20. FileSystemObject Object,  , http://msdn.microsoft.com/en-us/library/z9ty6h50(v=vs.84).aspx
  21. http://msdn.microsoft.com/en-us/library/windows/desktop/ms675944(v=vs.85).aspx,  , ADO Object Model
  22. ADO Fundamentals,  , http://msdn.microsoft.com/en-us/library/windows/desktop/ms680928(v=vs.85).aspx
close
IMAGE

Home 5

Business

Management

HBR 3

Information

Recreation

Hobbies 8

Culture

Chinese 1097

English 337

Reference 67

Computer

Hardware 151

Software

Application 198

Digitization 25

Latex 9

Manim 121

Numeric 19

Programming

Web 283

Unicode 494

HTML 65

CSS 58

ASP.NET 174

OS 389

DeskTop 7

Python 19

Knowledge

Mathematics

Formulas 8

Algebra 25

Number Theory 206

Trigonometry 18

Geometry 21

Calculus 67

Complex Analysis 21

Engineering

Tables 8

Mechanical

Mechanics 1

Rigid Bodies

Statics 92

Dynamics 37

Fluid 5

Fluid Kinematics 5

Control

Process Control 1

Acoustics 19

FiniteElement 2

Physics

Electric 27

Biology 1

Geography 1


Copyright © 2000-2020 Sideway . All rights reserved Disclaimers last modified on 06 September 2019