Total .NET Analyzer Rule Documentation  

CType Rule

Consider using DirectCast for performance reasons.

Remarks

Visual Basic .NET provides two options for casting:
CType: Casts or converts one type into another type. If the types do not match, coercion may be performed.
DirectCast: Casts one type to another type, but does not perform coercion if the types do not match.

Note that CType includes all of the VB conversion functions. These are CBool, CByte, CChar, CDate, CDec, CDbl, CInt, CLng, CObj, CShort, CSng, and CStr.

The main difference between the two is that DirectCast only works if the specified type and the run-time type of the expression are the same. For instance, the following DirectCast operation will fail because the run-time type of the object O is not an integer:


Dim O As Object = 1.5
Dim I As Integer = DirectCast(O, Integer) ' Causes a run-time error.
Dim I As Integer = CType(O, Integer) ' Does not cause a run-time error.

The DirectCast operation in this example, on the other hand, would succeed:

Dim O As Object = 1
Dim I As Integer = DirectCast(O, Integer) ' Succeeds.
Dim I As Integer = CType(O, Integer) ' Succeeds, but is slower than the DirectCast.

When converting from an object to a primitive type, the DirectCast operation has better performance than the CType operator. If coercion is necessary, however, you must still use the CType operation.

Resolution

Review the cast expression to determine whether type coercion is necessary. If no coercion is necessary (i.e. the run-time type of the value is the same as the type specified in the cast expression), use the DirectCast expression to increase application performance.

See Also

Cast Expressions

DirectCast