Pages

Wednesday, September 19, 2012

Option Strict places an even tighter grip on applications (VB .NET)

Many of you are familiar with the Option Explicit statement. When this feature is enabled, you can't use any undefined variables. Well, another option avaialable is Option Strict. When this feature is on, VB will flag any late bound statements and statements causing implicit conversions where data will be lost.

For example, the following code would fail the late binding Option Strict test:

Dim test3 As Object = Split("1,2,3", ",")
MsgBox(test3(0))

However, the following code would pass:

Dim test3() As Object = Split("1,2,3", ",")
MsgBox(test3(0))

Likewise, the following code would fail the conversion Option Strict test:

Dim i As Integer
TextBox1.Text = "34"
i = 360 * (CLng(TextBox1.Text) / 100)
MsgBox(i)

In cases such as this, you'd use the CType function to explicitly convert the result:

Dim i As Integer
TextBox1.Text = "34"
i = CType(360 * (CLng(TextBox1.Text) / 100), Integer)
MsgBox(i)


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.