Why Option Strict?
May 9th, 2007
Why should you use Option Strict?
VB programmers, like BASIC programmers before them, usually haven’t paid much attention to variable types. We commonly concatenated strings and number values together and did other such type conversions on the fly. So why would we want to restrict our freewheeling methods by using Option Strict?
The main reason is that it improves the quality of our code. Just like Option Explicit, which require variables to be declared, Option Strict helps us prevent bugs before they can happen. Bugs are much easier and less expensive to fix in the early stages of development and they become progressively more expensive as a project goes on. Conversion related errors plagued many VB6 and earlier applications. Often we would see intermittent, weird, bugs that were hard to track down and tricky to fix reliably. This was often called “evil type coercion”, or “ETC” for short, in VB6 circles. Thus, by using Option Strict, we avoid one of the most common problems encountered in classic VB development.
But what else happens if you don’t use Option Strict? Yes, the .NET Framework will do the conversion for you using the System.Object just like the VB6 runtime did with Variants. However, this has the same drawbacks as in VB6, difficult to trace bugs and a considerable performance hit. In fact, the performance hit is greater than using Variants in VB6 because of the additional conversion work the System.Object has to do.
If you turn on Option Strict in a existing project you may be shocked to see just how many poorly typed operations you have. It’s very likely to exceed the 100 or so errors that the Error List window holds. Don’t panic, it’s not that tough to replace them with the .NET conversion standard functions of DirectCast, TryCast or CType (I’ll discuss these in another article at some point). Making this fix to your code is a quick and easy way to improve your app’s performance and stability.
You will probably want to also take the step of turning on Option Strict for all your new applications. Unfortunately, the VB.NET IDE ships with Option Strict off, probably in order to make transition easier for VB6 programmers. To turn it on for your apps, open the Options Dialog from the Tools menu and navigate down the tree to “Projects and Solutions” and then “VB Defaults”. From the combo, select On, click OK and you’re done.

Entry Filed under: Tip Sheets
Rate This Article:











1 Comment Add your own
1. a00f7adf5756&hellip | May 14th, 2008 at 4:47 pm
a00f7adf5756
a00f7adf575665d302cb
Leave a Comment
Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
Trackback this post | Subscribe to the comments via RSS Feed