tags:

views:

31

answers:

2

Possible Duplicate:
Why use TryCast instead of Directcast ?

hi, I want to know about the trycast and direct cast in vb.net. What is the difference between them?

+1  A: 

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.

CraigTP
That sounds as if you would suggest always use TryCast instead of DirectCast. You should have better pointed out that DirectCast should be used as standard and TryCast only if the cast could fail.
Tim Schmelter
A: 

In short:

TryCast will return an object set to Nothing if the type being cast is not of the type specified.

DirectCast will throw an exception if the object type being cast is not of the type specified.

The advantage of DirectCast over TryCast is DirectCast uses less resources and is better for performance.

Code example:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    Dim auto As Car = New Car()
    ' animalItem will be Nothing
    Dim animalItem As Animal = GetAnimal_TypeCast(auto) 

    Dim cat As Cat = New Cat()
    ' animalItem will be Cat as it's of type Animal
    animalItem = GetAnimal_TypeCast(cat)  

    Try
        animalItem = GetAnimal_DirectCast(auto)
    Catch ex As Exception
        System.Diagnostics.Debug.WriteLine(ex.Message)
    End Try
End Sub

Private Function GetAnimal_TypeCast(ByVal animalType As Object) As Object
    Dim animalBase As Animal

    ' This will produce an object set to Nothing if not of type Animal
    animalBase = TryCast(animalType, Animal)

    Return animalBase

End Function

Private Function GetAnimal_DirectCast(ByVal animalType As Object) As Object
    Dim animalBase As Animal

    ' This will throw an exception if not of type Animal
    animalBase = DirectCast(animalType, Animal)

    Return animalBase

End Function
BobaFett