3

Are there any advantages of using Option Explicit Off in Visual Basic .NET? If it is Off it allows to use variables without declaring.

Here is example code with Option Explicit Off:

Option Explicit Off

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        i = 1

        MsgBox(i)
    End Sub

End Class

It works perfectly fine.

Should this be used? Is it useful in any specific scenarios?

Humayun Shabbir
  • 2,961
  • 4
  • 20
  • 33

2 Answers2

5

It works, but it does not mean you should do it. This kind of code is awful, and when you write program that are more complicated and big, things like that will cause troubles. I always use Option Expicit On, and I see no advantages of not using it. I also work with Option Strict On all the time, which may prevent many misfit calculation results.

For further reading, take a look here.

Eminem
  • 870
  • 5
  • 20
  • 2
    100% on this one. When you get into more complex code a simple spelling error can cause you lots of debug time (due to a new variable being created when your expecting an existing one to be used) – DarrenMB Aug 02 '14 at 11:23
5

First off, @Eminem is right and using Explicit (and Strict) will save you headache in the long run. I always use it and I recommend others do too.

But you asked if there were any scenarios where turning them off is useful, and there are. Otherwise, why would the options even exist, right?

If you are working on a small project that you know you're going to throw away at the end (i.e. just testing a concept, or making a one-off converter) then not having to declare variables saves a small amount of time, and who cares if you can't maintain it later, you're throwing it away.

Plus, if you're testing something, you may be changing variable types repeatedly, and having to go back to the top and re-declare every time can be a pain.

And if you're coming into VB from a language that doesn't even have explicit variable declaration, you might want to put off the variable declaration until you're more comfortable with some of the other differences.

But I've found that I never really throw anything away, and I am frequently going back to re-purpose some "throw away" I wrote years ago. The time I save making that easy outweighs (for me at least) the extra effort of declaring (or re-declaring) my variables.

I've also found that variable Type and Scope errors account for a huge fraction of bugs I encounter, anything the IDE can do to help me out there is much appreciated.

Robert Sheahan
  • 2,100
  • 1
  • 10
  • 12