Saturday, August 23, 2008

.net Casting - CType , DirectCast , TryCast

There are 3 ways of casting in .net. Here i'll give some explanation for each of it.

CType

Can be said most commonly used among the three. In project which i'm currently involved , Ctype is oftenly used in casting an object from FindControl to specific type. Ctype is alse used to cast a session that handle a datatable.

Ctype requires 2 parameter , the object and also the type.

Code Example :

Dim sessionFromDT as new DataTable

sessionFromDT = Ctype(Session("myDT"),DataTable)


DirectCast

Using DirectCast , you can only convert a type to another type that has inheritance or implementation relationship. I can't really explain this , but from what i read, using directCast for a double to integer ,will throw an exception because there are no relationship. But we can cast System.Windows.Forms.Form to System.Windows.Forms.Control. We can see that , both of this type inherit from the FORMS. Benefit of using this compare to CType is better perfomance because it doesn't rely on Visual Basic routine.



TryCast

This one is quite interesting to me, because CType , DirectCast will throw an exception when it fail to convert type. But, by using TryCast , we will get NOTHING. So , why do you want to write codes for handle exception when TryCast can handle it for you? Ok, we got NOTHING, proceed to the next code. Yeah, thats cool. But theres a limitation here, you can only convert reference types, such as classes and interfaces and it have the same condition as DirectCast , from and to types that have relationship.

No comments: