Why use TryCast instead of DirectCast?
The main difference between
CType) is that both
DirectCast will throw an
Exception, specifically an
InvalidCastException if the conversion fails. This is a potentially "expensive" operation.
TryCast operator will return
Nothing if the specified cast fails or cannot be performed, without throwing any exception. This can be slightly better for performance.
The MSDN articles for TryCast, DirectCast and CType say it best:
If an attempted conversion fails,
DirectCastboth throw an
InvalidCastExceptionerror. This can adversely affect the performance of your application.
Nothing(Visual Basic), so that instead of having to handle a possible exception, you need only test the returned result against Nothing.
DirectCastdoes not use the Visual Basic run-time helper routines for conversion, so it can provide somewhat better performance than
CTypewhen converting to and from data type