Visual Basic .NET provides two options for casting. CType casts or converts one type into another type. If the types don't match, coercion may be performed. DirectCast casts one type to another type with better performance than CType, but doesn't perform coercion if the types don't 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 runtime type of the expression are the same. This difference only appears when you're converting from an object type to a value type, or unboxing a value. For instance, the following DirectCast operation will fail because the boxed 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, will 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 you're converting from an object to a value type, or unboxing, the DirectCast operator has better performance than the CType operator. The Visual Basic .NET compiler generates four lines of IL code for DirectCast. However, using CType causes the Visual Basic .NET compiler to generate a call to a conversion method that's well over 100 lines of IL code. This method in turn calls other methods. In performance critical code, the difference can be substantial. If coercion is necessary, however, you must still use the CType operation, or perform the coercion manually. For example:
Dim O As Object = 1.5
Dim f As Single = DirectCast(O, Single) ' Cast to the runtime type
Dim i as Integer = CType(f,Integer) ' CType is OK here, since this cast does not unbox 'f'
To summarize, when you're type casting from an object type to a value type, or unboxing, you should first determine whether type coercion is necessary. If no coercion is necessary (i.e., the boxed type of the value is the same as the type specified in the cast expression), use the DirectCast expression to increase application performance.
This tip was detected with FMS Total .NET Analyzer. See http://www.fmsinc.com/dotnet/analyzer for more information.