Convert vs. CType
Asked Answered
O

2

14

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

Ontario answered 4/4, 2011 at 21:20 Comment(2)
Please stop putting the programming language in the question title... that's what tags are forMccaleb
Won't do it again. I've seen others do that, thought it might be a good idea. Thanks for the feedback.Ontario
A
11

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

Aristocracy answered 4/4, 2011 at 21:23 Comment(1)
Not true. CType was never in the VB6. I think you are confusing this with CInt, CDbl, etc.Diploid
D
4

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

Diploid answered 11/8, 2015 at 14:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.