DirectCast Operator (Visual Basic)

Introduces a type conversion operation based on inheritance or implementation.

Remarks

DirectCast does not use the Visual Basic run-time helper routines for conversion, so it can provide somewhat better performance than CType when converting to and from data type Object.

You use the DirectCast keyword similar to the way you use the CType Function and the TryCast Operator keyword. You supply an expression as the first argument and a type to convert it to as the second argument. DirectCast requires an inheritance or implementation relationship between the data types of the two arguments. This means that one type must inherit from or implement the other.

Errors and Failures

DirectCast generates a compiler error if it detects that no inheritance or implementation relationship exists. But the lack of a compiler error does not guarantee a successful conversion. If the desired conversion is narrowing, it could fail at run time. If this happens, the runtime throws an InvalidCastException error.

Conversion Keywords

A comparison of the type conversion keywords is as follows.

Keyword Data types Argument relationship Run-time failure
CType Function Any data types Widening or narrowing conversion must be defined between the two data types Throws InvalidCastException
DirectCast Any data types One type must inherit from or implement the other type Throws InvalidCastException
TryCast Operator Reference types only One type must inherit from or implement the other type Returns Nothing

Example

The following example demonstrates two uses of DirectCast, one that fails at run time and one that succeeds.

Dim q As Object = 2.37
Dim i As Integer = CType(q, Integer)
' The following conversion fails at run time
Dim j As Integer = DirectCast(q, Integer)
Dim f As New System.Windows.Forms.Form
Dim c As System.Windows.Forms.Control
' The following conversion succeeds.
c = DirectCast(f, System.Windows.Forms.Control)

In the preceding example, the run-time type of q is Double. CType succeeds because Double can be converted to Integer. However, the first DirectCast fails at run time because the run-time type of Double has no inheritance relationship with Integer, even though a conversion exists. The second DirectCast succeeds because it converts from type Form to type Control, from which Form inherits.

See also