1

I am using VB.NET, at the top is

Option Explicit

However why does the compiler not raise an error when I do :-

obj.ThisFunction(Convert.ToInt32(strMessage))

and the function is :-

Function ThisFunction(id as long)

Surely, Int32 is int and int64 is long? Is there a compiler option in VS 2013 that I can turn on to spot these?

Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
MiscellaneousUser
  • 2,915
  • 4
  • 25
  • 44
  • VB.NET compiler automatically convert Int32 to long. – Sandeep Kumar May 10 '16 at 11:52
  • If you want to spot type errors, use `OPTION STRICT ON`. But implicit integer to long conversion is still allowed. – sloth May 10 '16 at 11:56
  • Yes, the value in strMessage can now be very long and Convert.ToInt32 will cause a run time error. It'll be a nightmare going through all the code looking for and upsizing every ToInt32. If I can do that easily with an error list, that'll be good. Strict was on as well :( – MiscellaneousUser May 10 '16 at 11:57
  • 1
    Since your `strMessage` variable won't be populated until runtime, how do you expect the compiler to catch that error? The compiler has absolutely no way to know what will be in that variable. – Chris Dunaway May 10 '16 at 14:28

1 Answers1

4

This is not a compile error. If you have written code to explicitly convert strMessage to an Int32, then the compiler assumes you knew what you were doing here.

In order to check this is actually an Int32 you can use Int32.TryParse

Converting an Int32 to an Int64 is not a compile error even with Option Strict On because this is a widening conversion (Option Strict On gives a compilation error when it finds implicit narrowing conversions, amongst other things)

Matt Wilko
  • 26,994
  • 10
  • 93
  • 143