VB.NET Option Explicit [On | Off]
Option Explicit statement ensures whether the compiler requires all variables to be explicitly declared or not before it use in the program.
Option Explicit [On Off]
The Option Explicit has two modes. On and Off mode. If Option Explicit mode in ON , you have to declare all the variable before you use it in the program . If not , it will generate a compile-time error whenever a variable that has not been declared is encountered .If the Option Explicit mode is OFF , Vb.Net automatically create a variable whenever it sees a variable without proper declaration.
By default the Option Explicit is On
With the Option Explicit On , you can reduce the possible errors that result from misspelled variable names. Because in Option Explicit On mode you have to declare each variable in the program for storing data.
Take a look at the following programs, it will give you a clear picture of Option Explicit.
The following program is a normal vb.net program , so the default mode of Option Explicit On is using. The default is Option Explicit On , so we do not need to put it in the source code.
VB.NET Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim someVariable As String someVariable = "Option Explicit ON" MsgBox(someVariable) End Sub
The above program , declare a String variable and assigned a value in it and it displays.
Take a look at the following program , it is an example of Option Explicit Of
Here "someVariable" is not declared , because the Option Explicit Of , without any compiler error you can continue the program.