Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert vs. CType

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! = )

like image 705
Phonon Avatar asked Apr 04 '11 21:04

Phonon


People also ask

What is the difference between DirectCast and CType?

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.

What does CType mean in Visual Basic?

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.

What is the use of DirectCast in VB net?

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.

Is used to convert an object or variable of one type into another?

You convert an Object variable to another data type by using a conversion keyword such as CType Function.


2 Answers

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().

like image 77
Bala R Avatar answered Oct 07 '22 01:10

Bala R


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).

like image 29
Matt Wilko Avatar answered Oct 07 '22 03:10

Matt Wilko