Search code examples
vb.netfor-loopscope

Scope of for loop counter in Visual Basic


Consider the following

Dim nofTries As Integer
For nofTires = 1 To 5
    If (condition) Then Exit For
Next 

Where due to a typo the loop counter is different than the variable declared. Yet, despite the "option explicit" on-setting, NO compiler warning or error was given, and this acted as if:

Dim nofTries As Integer
For nofTires As Integer = 1 To 5
    If (condition) Then Exit For
Next 

Is there an explanation for why the compiler took it upon itself to assume a type instead of giving an error?


Solution

  • This has to do with OPTION INFER being ON. Turn it off and the desired compiler error will appear. The source of the misunderstanding for me was this option doesn't really exist in VBA, but also that it seems to be on by default where off seems more reasonable.