DirectCast Operator (Visual Basic)


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

Introduces a type conversion operation based on inheritance or implementation.

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.

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.

A comparison of the type conversion keywords is as follows.

KeywordData typesArgument relationshipRun-time failure
CType FunctionAny data typesWidening or narrowing conversion must be defined between the two data typesThrows InvalidCastException
DirectCastAny data typesOne type must inherit from or implement the other typeThrows InvalidCastException
TryCast OperatorReference types onlyOne type must inherit from or implement the other typeReturns Nothing

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.

Widening and Narrowing Conversions
Implicit and Explicit Conversions