Thursday, November 1, 2007

Option Explicit and Option Strict in VB .NET

Generally it is a MUST to put ‘Option Explicit’ and ‘Option Strict’ at the top of all my .net classes.

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
Option Strict’ keeps VB developers coding bad casts. 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 and restricts implicit type conversions, so that you can avoid them. It also verifies that functions have return types and all paths return a value. it helps to catch lot of possible errors, but it is off by default.

To enable the Option Strict and Option Explicit statements in the code-behind files and files that are contained in the App_Code folder of a Visual Basic application, add the following code to the Web.config file:
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="0" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="0" />
</compilers>
</system.codedom>

3 comments:

Anonymous said...

This has been a bug since Visual Studio 2005. And still affects VS 2008 SP1. Microsoft should add a provider option for this in the compiler section. The workaround posted above is what Microsoft has suggested. However this does not work in Partial Trust environments (hosting). The only workaround is to add Option Strict to the top of every code file (or modify the VS templates to do so)

Anonymous said...

Good fill someone in on and this fill someone in on helped me alot in my college assignement. Say thank you you seeking your information.

Anonymous said...

Hi - I am definitely happy to discover this. Good job!

 

Get paid for your opinions! Click on the banner above to join Planet Pulse. Its totally free to sign up, and you can earn UNLIMITED. Find out more by visiting PLANET PULSE.
Sign up for PayPal and start accepting credit card payments instantly. http://www.emailcashpro.com
July Code Blog Copyright © 2010 Blogger Template Designed by Bie Blogger Template