CTYPE, DIRECTCAST AND TRYCAST

November 21, 2008 at 5:07 pm | Posted in ASP.NET | 5 Comments
Tags: , , , ,

CTYPE is most commonly used one. But if you are converting types other than the underlying type of an object
CType can convert the underlying object to a new instance of an object of a different type.

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

Code Example :
varObject =1;
varString = CType(varObject, String)

varObject =1;
varString = CType(varObject, String)

Directcast can only convert a type tp another type that has inheritance or implementation relationship. It can be used  to convert objects to their actual type, can’t convert into some other type.

For example :
varObject = “1”; //varObject is of type “Object” Actual type is String
varString = DirectCast(varObject, String); //This will work

The above code will work as the object’s actual type is string. Now check the below code where the object’s actual type is integer.

varObject = 1; //varObject is of type “Object” Actual type is integer
varString = DirectCast(varObject, String); //This will not work. Throws an exception

Another Example : Casting System.windows.Forms.form to System.Windows.Forms.Control.

Which one is better:
1)use Directcast when possible to convert objects to their  nderlying types instead of Ctype because it is faster than CTYPE.
2)Readability : DirectCast is not vb.net specific, portal to other language. Other language programmers can easily read and understand the code written by you. It is a much more “intentional” way of coding than CType.
3)DirectCast is twice faster than CTYPE for value type. But same performance for refernce type.

TryCast
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)
You need’t to write codes for handle exception when TryCast can handle it for you. But there are some limitations
1)TryCast operates only on reference types, such as classes and interface.

Code Sample:
varObject = “1”; //varObject is of type “Object” Actual type is String
varString = TryCast(varObject, String);

C# equivalent to trycast[VB.Net] is “as”

Code Sample:
varObject = “1”; //varObject is of type “Object” Actual type is String

varString = varObject as String;


Entries and comments feeds.