Phonon
Phonon

Reputation: 12727

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

Upvotes: 14

Views: 3430

Answers (2)

Matt Wilko
Matt Wilko

Reputation: 27322

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

Upvotes: 4

Bala R
Bala R

Reputation: 108937

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

Upvotes: 11

Related Questions