Sunday 22 July 2012

Option Strict [On Off] in vb.net

Option Strict is prevents program from automatic variable conversions, that is implicit data type conversions .

Option Strict [On Off]

By default Option Strict is Off

From the following example you can understand the use of Option Strict.

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 longNum As Long
Dim intNum As Integer
longNum = 12345
intNum = longNum
MsgBox(intNum)
End Sub
  End Class

The above program is a normal vb.net program and is in default Option Strict Off . Because its Option Strict Off we can convert the value of Long to an Integer.

Take a look at the following program.

Download Source CodePrint Source Code
Option Strict On
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click

        Dim longNum As Long
        Dim intNum As Integer

        longNum = 12345
        intNum = longNum

        MsgBox(intNum)
    End Sub
End Class

When you write this source code the compiler will shows the message
"Option Strict On disallows implicit conversions from 'Long' to 'Integer'"

The compiler generate error because in the program we put "Option Strict On" and prevent the program from automatic conversion.

No comments:

Post a Comment