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.