| Business Application Development with: SQL Server, C#, VB, VB.Net, ASP, ASP.Net, and XML |
| N | S |
Novick Software Management • Design • Programming • Training • Consulting |
|
|
News Links Schedule Site Map Contact |
|
Tips and Tricks for: Visual Basic.NetThe Problem: What is the difference between CType and DirectCastThere 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.
|
|
|
Copyright © 2003-2008 Novick Software, Inc. | Terms of Use | Privacy Policy | Nice Things People Say| |