Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

11.11 Cast Expressions

Visual Studio .NET 2003

A cast expression coerces an expression to a given type. Specific cast keywords coerce expressions into the primitive types. Two general cast keywords, CType and DirectCast, coerce an expression into any type.

DirectCast is different from CType in the way it converts expressions that are typed as Object. When converting an expression of type Object whose run-time type is a primitive value type, DirectCast throws a System.InvalidCastException exception if the specified type is not the same as the run-time type of the expression or a System.NullReferenceException if the expression evaluates to Nothing. If the specified type and the run-time type of the expression are the same, however, the run-time performance of DirectCast is better than that of CType.

If no conversion exists from the type of the expression to the specified type, a compile-time error occurs. Otherwise, the expression is classified as a value and the result is the value produced by the conversion.

CastExpression ::=
   DirectCast ( Expression , TypeName ) |
   CType ( Expression , TypeName ) |
   CastTarget ( Expression )
CastTarget ::=
   CBool | CByte | CChar | CDate | CDec | CDbl | 
   CInt | CLng | CObj | CShort | CSng | CStr

See Also

11.4 Simple Expressions | 11.8 Invocation Expressions | 11.6 Member Access Expressions | 11.9 Index Expressions | 11.10 New Expressions | 11.3 Late-Binding Expressions | 9.2.5.2 Reference Parameters | Conversion Functions (Visual Basic Language Reference) | Type Conversions (Visual Basic Language Concepts)

Show:
© 2015 Microsoft