A friend and coworker asked me today why I use ‘Option Explicit’ and ‘Option Strict’ at the top of all my .net (and for that matter VB6/asp 3.0) classes. I thoguht I’d record the answers here.
‘Option Explicit’ ensures you declare all variables before use. VB.NET doesn’t allow this anymore but in the past it was possible to build an entire application without declaring a single variable!
‘Option Strict’ keeps VB developers coding bad casts as below:
dim x as string = “true”
dim y as boolean = x
or
dim ctl as control
ctl = new textbox
If you’re pure C# you probably can’t believe that this is actually possible. Well it is. More to the point VB developers have bad habits from the ‘days of old’ and code things like this without even batting an eyelid. NOTE: By default VB.NET still allows these bad casts
Option Explicit Statement
By default, the Visual Basic .NET or Visual Basic 2005 compiler enforces explicit variable declaration, which requires that you declare every variable before you use it.
Option Strict Statement
By default, the Visual Basic .NET or Visual Basic 2005 compiler does not enforce strict data typing.
In Visual Basic .NET, you can convert any data type to any other data type implicitly. Data loss can occur when the value of one data type is converted to a data type with less precision or with a smaller capacity. However, you receive a run-time error message if data will be lost in such a conversion. Option Strict notifies you of these types of conversions at compile time so that you can avoid them.
23 January, 2007 at 4:57 pm |
Excellent methods to implement.
I can say from experience it will reduce the occurrence of bugs/errors appearing in your software drastically.
asif
29 January, 2007 at 6:43 pm |
Mr Gaskell nice article.
One thing i will add, something that makes life a little easier is;
In Visual Studio 2005 if you select Tools -> Options, then in the Options window expand Projects and Solutions, there is a section called VB Defaults where you can switch on or off (why you would i don’t know) Option Explicit and Option Strict for all future projects.
Cheers mate
Wes
29 January, 2007 at 10:51 pm |
Thanks Wes, good tip didn’t know it was in there.
Chris.
3 February, 2007 at 1:49 pm |
Another VB.Net idiosyncracy.
In VB.Net 2003 (Not sure about 2005 since I don’t do VB these days) you can turn on so called advanced members, tools > options > text editor > basic, remove the tick from “hide advanced members”. Gives all you VB’ers the advanced members such as the ever powerful “ToString” on the Object object…….
27 June, 2008 at 7:05 am |
i found one tutorial about option explicit and option strict . it in basic level
http://vb.net-informations.com/language/vb.net_option_explicit.htm
http://vb.net-informations.com/language/vb.net_option_strict.htm
hope it will help u to understnd more