N S

Novick Software Management • Design • Programming • Training • Consulting

   

 

 

Tips and Tricks for:  Visual Basic.Net

The Problem:   What is the difference between CType and DirectCast

There are two functions that change the type that the VB.Net compiler identifies with an object: CType and DirectCast.  So which one should you use?


Solution: If you're totally sure that the expression is the same type that it's being cast to, use DirectCast. If there is any doubt, use CType.

The difference between the two keywords is that CType succeeds as long as there is a valid conversion defined between the expression and the type and DirectCast requires that the run-time type of an object variable to be the same as the specified type that it's being cast to.  Really the same, not just that one can be converted to the other.

Use DirectCast if you're absolutely positively sure that an object is the specified type and the run-time type of the expression are the same.  If you're not sure but expect that the conversion will work, use CType.   The run-time performance of DirectCast is better than that of CType. However, DirectCast throws an InvalidCastException error if the argument types do not match, so you must be sure.
.


RSS as HTML

Personal Blog

 
New Tips:

Loading SQL Profiler trace (.trc) files with fn_trace_gettrace

Upcoming
Presentations:

Big Data:
Working with Terabytes
in SQL Server

July 9 '08


Full Schedule