2

CInt will succeed with "1.2" while Integer.Parse will fail, are there some values that CType will succeed with where CInt, CDec or CStr will fail? When should CType be used?

jmoreno
  • 12,752
  • 4
  • 60
  • 91
  • 1
    You could check this answer http://stackoverflow.com/a/423910/130611 or check the [documentation](https://msdn.microsoft.com/en-us/library/s2dy91zy.aspx). – the_lotus Oct 13 '16 at 15:55
  • CType also allows for conversion to more complex types such as TextBox. – Ryan Thomas Oct 13 '16 at 15:55
  • @the_lotus: no, that is an entirely different matter. – jmoreno Oct 13 '16 at 15:57
  • @the_lotus: and the documentation doesn't cover what this question is asking. CType is used exactly 4 times on that page, and does not directly refer to any of the other type conversion functions – jmoreno Oct 13 '16 at 16:10
  • 1
    Possible duplicate of [Integer.Parse vs. CInt](http://stackoverflow.com/questions/423820/integer-parse-vs-cint) – Heinzi Oct 13 '16 at 16:19
  • 2
    @Heinzi The question asks what is the difference between `CInt()` and `CType( , Integer).` Your proposed duplicate is about the difference between `CInt()` and `Integer.Parse(),` and doesn't even mention `CType().` – Blackwood Oct 14 '16 at 01:07
  • @Blackwood: Point taken. I retracted my close vote. – Heinzi Oct 14 '16 at 06:57

1 Answers1

5

There is no difference between using CType and using CXXXX, in fact they compile to the same IL, e.g. a call to Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger for CInt or CType(,Integer), to Microsoft.VisualBasic.CompilerServices.Conversions.ToDecimal for CDec or Ctype(, Decimal) and to Microsoft.VisualBasic.CompilerServices.Conversions.ToString for CStr or Ctype(,String).

CType can be used on more than the primitive types, and can be used in generics, but outside of that, there is no concrete reason to prefer one syntax over the other. They will compile down to the same IL and so produce the same results in the same amount of time.

jmoreno
  • 12,752
  • 4
  • 60
  • 91