N S

Novick Software
SQL Server Consulting • Design • Programming • Training

  andy novick is a sql server mvp

 

 

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:

Use dsinit to set the SQL Server instance for Windows Azure dev storage

Upcoming
Presentations:

SQL Server
Loadfest R2
Sept 24

NEVB
Sept 2
SQL Azure

Code Camp 14
Oct 2, 2010
Data Dude
SQL Azure


Full Schedule