Subscribe to lar3ry's Blog        RSS Feed

Why Option Strict is a Great Idea

Icon Leave Comment
I'd like to point out a few benefits to using Option Strict that might not be readily apparent from reading the MSDN docs.

First, there are several types of errors that can be caused by improper data types. Many of these are fairly straightforward, but some can be obscure and hard to troubleshoot. The problems come when the compiler makes a conversion for you, and then you operate on the converted variable. One of the simplest problems can be illustrated as follows (assume you have not put in an Option Strict On statement):

Dim txt1 As String = "100"
Dim txt2 As String = "150"
Dim total as Integer = txt1 + txt2

What happened? Well, the compiler, instead of adding two numbers, concatenated the two strings, because "+" is an overloaded operator that does the same thing as "&". So now, the concatenated strings have a value of "100150", and assigning that value to total, gives the number 100150, and it did all this without letting you know that you had an error in logic.

If you use Option Strict, you will not be able to compile and run the program, because the compiler will insist on you using the right data type. Once you fix that, the program will compile and run, giving you the right answer in the MessageBox.

Now you might think that this will cause you a lot of extra work in writing your code, but it won't, really.

When you have that Option turned on, every time you have a data-type mismatch, you will be informed of the error by the presence of a little wiggly line under the offending line (or part of a line). If you move your mouse cursor over the wiggly line, you will be shown the error in a popup tooltip. Often, a small red underline will show up at the end of the wiggly line, and if you move your mouse cursor over that, a red exclamation mark will appear. Click on that, and you will usually be shown a suggestion on how to fix the problem. Clicking on the suggestion will apply the correction. So you see, you can actually save keystrokes, in addition to knowing that any bugs you have are not likely to be due to improper data types.

The real beauty of Option Strict is that it will make you aware of what, exactly your data types are, or what they should be. It doesn't take much browsing through the questions here, to find examples where someone had a problem because he tried to assign a control to a string variable, instead of assigning a property (.Text perhaps?) of that control. Option Strict will make you a better programmer, and you may just find yourself continuing to use it long after setting data types becomes second-nature to you.

0 Comments On This Entry


Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

May 2018

2021222324 25 26


    Recent Entries

    Search My Blog

    0 user(s) viewing

    0 Guests
    0 member(s)
    0 anonymous member(s)