I am somewhat confused about presence of two seemingly identical VB.NET functions: CType(args)
and Convert.ToType(args)
. I'm fairly new to .NET and VB in general, so I'm not quite sure whether one of them is a VB6 legacy or they actually have different purposes / uses / limitations. Is one of the them newer / safer? Are there reasons to use one but not the other?
Cheers! = )
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.
CType is compiled inline, which means that the conversion code is part of the code that evaluates the expression. In some cases, the code runs faster because no procedures are called to perform the conversion.
You use the DirectCast keyword similar to the way you use the CType Function and the TryCast Operator keyword. You supply an expression as the first argument and a type to convert it to as the second argument. DirectCast requires an inheritance or implementation relationship between the data types of the two arguments.
You convert an Object variable to another data type by using a conversion keyword such as CType Function.
CType is from VB6 times and is not the best when it comes to efficiency. You should be able to use Convert.ToXxxx()
methods for convertion and TryCast()
and DirectCast()
for casting instead of CType()
.
See this page on MSDN. (Conversion Functions, CType, DirectCast, and System.Convert Section).
The conclusion of that section is as follows:
Recommendation: For most conversions, use the intrinsic language conversion keywords (including CType) for brevity and clarity and to allow compiler optimizations when converting between types. Use DirectCast for converting Object to String and for extracting value types boxed in Object variables when the embedded type is known (that is, coercion is not necessary).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With