Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is TryCast and direct cast in VB.NET? [duplicate]

Tags:

vb.net

Possible Duplicate: Why use TryCast instead of DirectCast?

I want to know about TryCast and DirectCast in VB.NET. What is the difference between them?

like image 494
Red Swan Avatar asked Sep 17 '25 02:09

Red Swan


1 Answers

The main difference between TryCast and DirectCast (or CType) is that both CType and DirectCast will throw an Exception, specifically an InvalidCastException if the conversion fails. This is a potentially "expensive" operation.

Conversely, the 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, CType and DirectCast both throw an InvalidCastException error. This can adversely affect the performance of your application. TryCast returns Nothing (Visual Basic), so that instead of having to handle a possible exception, you need only test the returned result against Nothing.

and also:

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.

like image 101
CraigTP Avatar answered Sep 18 '25 15:09

CraigTP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!