Figure 3-12. Option Strict disables automatic narrowing of data.

Here, we have enabled Option Strict on a single file within our project. This approach can be useful when you wish to selectively allow narrowing conversions within specific *.vb files. However, if you wish to enable Option Strict for each and every file in your project, you can do so using the Compile tab of the My Project dialog box, as shown in Figure 3-13.

Figure 3-13. Enabling Option Strict on the project level

Note Under Visual Studio 2008, Option Strict is disabled for new Visual Basic 2008 projects. I would recommend, however, that you always enable this setting for each application you are creating, given that it is far better to resolve problems at compile time than runtime!

Now that we have some compile-time checking, we are able to resolve the error using one of two approaches. The most direct (and often more favorable) choice is to simply redefine the variable to a data type that will safely hold the result. For example:

Sub Main()

Console.WriteLine("***** The Amazing Addition Program *****") Dim a As Short = 30000 Dim b As Short = 30000

' Can no longer use: ' Dim answer As Short = Add(a, b)

End Sub

Another approach is to make use of an explicit Visual Basic 2008 type conversion function, such as CByte() for this example:

Sub Main()

Dim myByte As Byte

Dim myInt As Integer = 200

' This will no longer work: ' myByte = myInt myByte = CByte(myInt)

Console.WriteLine("Value of myByte: {0}", myByte) End Sub

Was this article helpful?

0 0

Post a comment