What do Option Strict and Option Explicit do?

前端 未结 3 1150
天命终不由人
天命终不由人 2020-11-21 07:37

I saw this post:

Typos… Just use option strict and explicit please.. during one software development project, which I was on as a consultant, they w

3条回答
  •  北恋
    北恋 (楼主)
    2020-11-21 08:11

    TL;DR

    Option Strict and Option Explicit help you to catch potential and actual errors at design time, rather than your code compiling and failing at runtime. You should switch both On.

    Option Strict and Option Explicit are Off by default. To switch them on:

    Option Strict Tools -> Options -> Projects and Solutions -> VB defaults -> Option Strict. Set it to On.

    Option Explicit Tools -> Options -> Editor -> Require Variable Declaration. tick it.

    Option Explicit

    With Option Explicit Off you don't have to declare (Dim) a variable before using it:

    a = 123 'a is automatically declared as an Integer

    This becomes dangerous when you declare a variable in one place and think you are using it later but mis-type it:

    Dim counter As Integer = 0
    'some lines later...
    countr = 55 'This creates a new variable called countr 
    

    Or even worse, you assign a value to a variable that you think is in scope, but it isn't and you end up declaring a new variable with the same name but differing scope.

    With a lot of code or long methods these can be easy to miss so you should always switch it on to prevent these sorts of issues.

    Option Strict

    With Option Strict Off you can implicitly convert a datatype to a narrowing type with no error:

    Dim d As Double = 999.99
    Dim s As Single = d 'No error with Option Strict Off
    

    For these cases Option Strict serves as a warning to the developer to make sure that the double value should never exceed Single.MaxValue.

    You can also assign an Enum to the incorrect value with no error. The following is a real example of this:

    enter image description here

    The variable should have been set to EOpticalCalStates.FAILED (24), in fact it sets the State to a value of 4 which is equivalent to EOpticalCalStates.ALI_HOR.

    Something like this is not easy to spot.

    Therefore you should always have Option Strict on by default. This setting should have been set on as default, but Microsoft decided to leave it off to increase backwards compatibility (which with hindsight was a mistake IMO).


    If you have started a project before setting the default for new projects, you will need to use:

    "Project" menu -> " Properties..." item -> "Compile" tab -> set "Option strict" to "On".

提交回复
热议问题