3

Here are peculiar results I get from this simple piece of code.

Say you want to create a variable of type string, without declaring it as a string. You can do this and get no errors from the compiler:

Option Strict On

' Produces no errors:
Dim MyString = "Random String"

You can also do this and not get any errors:

Option Infer Off
' Produce no errors as well.
Dim MyString = "Random String"

But, when you combine both Option String On and Option Infer Off, there is an error:

Option Strict On
Option Infer Off

' The following line generates an error -
' Option Strict On requires all variable declarations to have an "As" clause
Dim MyString = "Random String"

Why does Option Strict need to be combined with Option Infer? Especially when the error specifically says that the following error is an "Option Strict" type. Why can't Option Strict alone find that line as an error?

jmoreno
  • 12,752
  • 4
  • 60
  • 91
Eminem
  • 870
  • 5
  • 20
  • See [http://msdn.microsoft.com/de-de/library/bb384665.aspx](http://msdn.microsoft.com/de-de/library/bb384665.aspx). There is a table with possible combinations of these declarations. – Fratyx Oct 02 '14 at 19:48
  • With "option strict On" and "Infer Off" `Dim MyString = "Random String"` doesn't compile(contrary to your statement) because the `As`-clause is missing. If both are `Off` the string is actually an object (you can see it if you try `MyString.Length` which does not work). If Infer is `On` the string-literal is correctly detected as string. – Tim Schmelter Oct 02 '14 at 19:53
  • @TimSchmelter: You don't see an "Option Infer On" for the first example, but it's probably true at the project level. The compiler uses the project Option settings unless overridden at the file level. – Dave Doknjas Oct 02 '14 at 22:16
  • @DaveDoknjas: i have assumed that the first example uses option infer on, but the second is _off_. But OP mentioned that this does work which is not true. At least if it's still _strict_. If _strict_ is also _off_ the "string" is treated as object. – Tim Schmelter Oct 02 '14 at 22:36
  • @TimSchmelter: At the project level, Option Strict is off by default and Option Infer is on by default. That's consistent with the OP's assertions. This leads to the first being inferred as a string, the second being implicitly declared as an 'Object'. – Dave Doknjas Oct 02 '14 at 22:45

1 Answers1

1

You're ignoring your project-level Option settings - these will determine the errors/warnings unless overridden at the file level. Look at the compile tab of the project properties for these.

Your project-level Option Infer is probably set to 'On', so your first example is actually identical to including "Option Infer On".

Dave Doknjas
  • 6,394
  • 1
  • 15
  • 28