none
Option Strict On, Option Strict Off RRS feed

  • Question

  • I am trying to do the right thing and operate my application using Option Strict On.

    However, this already cause me a problem that I cannot seem to figure out to fix.

    In the load form event the following code block is used.

            If glbblnOpen = True Then
               Some action
            End If

    With Option Strict Off the code block executes with no known errors.

    With Option Strict On the code block above throws an error telling me that, "Is" operator should be used instead of "=" operator.  Of course the obvious thing for me to do would be to replace the = with Is, which then tells me that must reference a nullible type operand.  All of which means something less than nothing to me. 

    Perhaps someone might be kind enough to explain to me what is required to make this work using Option Strict On?


    gwboolean

    Sunday, July 5, 2015 1:01 AM

Answers


  • glbblnOpen is a public global boolean variable.  In this case it might have been set to true prior to this form being opened.


    gwboolean

    If it's a boolean then what you posted should work (although it's redundant).

    Something isn't quite right here - are you quite sure it's a boolean?

    ***** EDIT *****

    Example:

    Option Strict On Option Explicit On Option Infer Off Public Class Form1 Private glbblnOpen As Boolean = False Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Load If glbblnOpen Then ' Some action Else ' Some other action End If Stop End Sub End Class



    Still lost in code, just at a little higher level.

    :-)


    • Edited by Frank L. Smith Sunday, July 5, 2015 1:22 AM ...added example code
    • Marked as answer by gwboolean Sunday, July 5, 2015 1:31 AM
    Sunday, July 5, 2015 1:18 AM

All replies

  • GW,

    Let's add one more to it - to create the "tightest" code possible:

    Option Strict On
    Option Explicit On
    Option Infer Off

    That's my de facto standard.

    It's critical to understand what's what and why.

    As for what you posted, we have no idea what your variable "glbblnOpen" is.


    Still lost in code, just at a little higher level.

    :-)

    Sunday, July 5, 2015 1:07 AM
  • Holy crap, wasn't Option Strict On enough???????

    OK, I can see I am going to have to go back and find some good reference reading material to provide me with an understanding of what all of these things are supposed to do for me and what I have to do to be able to work with them.  So is there a quick and dirty lesson on Strict/Explicit/Infer?

    glbblnOpen is a public global boolean variable.  In this case it might have been set to true prior to this form being opened.


    gwboolean

    Sunday, July 5, 2015 1:14 AM

  • glbblnOpen is a public global boolean variable.  In this case it might have been set to true prior to this form being opened.


    gwboolean

    If it's a boolean then what you posted should work (although it's redundant).

    Something isn't quite right here - are you quite sure it's a boolean?

    ***** EDIT *****

    Example:

    Option Strict On Option Explicit On Option Infer Off Public Class Form1 Private glbblnOpen As Boolean = False Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Load If glbblnOpen Then ' Some action Else ' Some other action End If Stop End Sub End Class



    Still lost in code, just at a little higher level.

    :-)


    • Edited by Frank L. Smith Sunday, July 5, 2015 1:22 AM ...added example code
    • Marked as answer by gwboolean Sunday, July 5, 2015 1:31 AM
    Sunday, July 5, 2015 1:18 AM
  • glbblnOpen is set as a boolean, (and False) in a mod file I use.

    It was set to True prior to this form being called.

    Now if I have nothing for the line, "Option Strict On", it does execute.


    gwboolean

    Sunday, July 5, 2015 1:24 AM
  • glbblnOpen is set as a boolean, (and False) in a mod file I use.

    It was set to True prior to this form being called.

    Now if I have nothing for the line, "Option Strict On", it does execute.


    gwboolean


    Is it showing a compile error (blue squiggly line) or does it compile and you get a runtime exception? If so, what exception?

    Still lost in code, just at a little higher level.

    :-)

    Sunday, July 5, 2015 1:26 AM
  • Got it!  Although I do not readily see how that makes the code better, but I am willing to accept that.  Now I guess I need to give some thought the other options.

    Thanks


    gwboolean

    Sunday, July 5, 2015 1:32 AM
  • As Frank recommended you should be using those settings and it's best to set them in the options dialog in the IDE

    Here are some samples to consider. First one has Option Strict Off and is unwise as we can declare the variable as it should be, Boolean.

    Option Strict Off
    Option Infer Off
    Module NotExcelModule1
        Public glbblnOpen ' Object
        Private Sub demo1()
            glbblnOpen = True
        End Sub
    End Module

    Moot point even with typing the variable the compiler does not need to guess but if there is other code that is not typed we are back at making the compiler work

    Option Strict Off
    Option Infer Off
    Module NotExcelModule1
        Public glbblnOpen As Boolean
        Private Sub demo1()
            glbblnOpen = True
        End Sub
    End Module

    Correct

    Option Strict On
    Option Infer Off
    Module NotExcelModule1
        Public glbblnOpen As Boolean
        Private Sub demo1()
            glbblnOpen = True
        End Sub
    End Module

    Requires Option Infer On

    Option Strict On
    Option Infer On
    Module NotExcelModule1
    
        Private Sub demo1()
            Dim keys() As Integer = {1, 2, 4, 5, 7}
    
            Dim arrayWithFirstMissingKey = keys.Select(
                Function(key, index) _
                    New With
                    {
                        Key .Key = key,
                        Key .Index = index
                    }
                ).Where(
                Function(tuple) (tuple.Index + 1 < keys.Length) AndAlso
                    (keys(tuple.Index + 1) > tuple.Key + 1)).Select(
                    Function(tuple) tuple.Key + 1).Take(1).ToArray()
    
            If arrayWithFirstMissingKey.Length > 0 Then
                MsgBox(String.Format("[{0}]", arrayWithFirstMissingKey(0)))
            End If
    
        End Sub
    End Module
    

    That's what one might think if they selected it off the web but we can fix it easily

    Option Strict On
    Option Infer Off
    Module NotExcelModule1
    
        Private Sub demo1()
            Dim keys() As Integer = {1, 2, 4, 5, 7}
    
            Dim arrayWithFirstMissingKey As Integer() = keys.Select(
                Function(key, index) _
                    New With
                    {
                        Key .Key = key,
                        Key .Index = index
                    }
                ).Where(
                Function(tuple) (tuple.Index + 1 < keys.Length) AndAlso
                    (keys(tuple.Index + 1) > tuple.Key + 1)).Select(
                    Function(tuple) tuple.Key + 1).Take(1).ToArray()
    
            If arrayWithFirstMissingKey.Length > 0 Then
                MsgBox(String.Format("[{0}]", arrayWithFirstMissingKey(0)))
            End If
    
        End Sub
    End Module
    

    So the point on the last two examples is that without proper knowledge one will gravitate to Option Strict Off or if they came from programming in VB6.

    Like anything we work with it's wise to study the "why" things are done a particular way.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my webpage under my profile but do not reply to forum questions.

    Sunday, July 5, 2015 1:35 AM
    Moderator
  • Got it!  Although I do not readily see how that makes the code better, but I am willing to accept that.  Now I guess I need to give some thought the other options.

    Thanks


    gwboolean

    Let me give you some background material, but I hope you'll consider it and come back to this and let's discuss this more. It's so very important to not "assume" type:

    Option Strict

    Option Explicit

    Option Infer


    Still lost in code, just at a little higher level.

    :-)

    Sunday, July 5, 2015 1:38 AM
  • Kev,

    ... yea, but you know how I feel about anonymous types! ;-)


    Still lost in code, just at a little higher level.

    :-)

    Sunday, July 5, 2015 1:39 AM
  • Thanks Kevin.  I get that, some of it anyway.  It does help to have some background as to what that is all for though.

    gwboolean

    Sunday, July 5, 2015 1:43 AM
  • It does help to have some background as to what that is all for though.

    I don't know, but I have to think this is a "left-over" from MS's attempt to transition the VB legacy people into VB Net.

    In my opinion only, that was a bad decision.


    Still lost in code, just at a little higher level.

    :-)

    Sunday, July 5, 2015 1:46 AM
  • Kev,

    ... yea, but you know how I feel about anonymous types! ;-)


    Still lost in code, just at a little higher level.

    :-)

    I highly recommend that anonymous types only be used when necessary. Example, I do a lot with backend services working between C#/VB.NET to JavaScript and JSON where there are situations that one deals with no types.

    Then there are times when we have short pieces of code

    Public Class Form1
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim Items As New List(Of String) From
            {
                "do you like tea",
                "Well that coffee was great",
                "interesting",
                "tea",
                "creame",
                "beep"
            }
            Dim Result =
                (
                    From T In Items _
                    .Select(Function(Token, Index) _
                                New With
                                {
                                    .Word = Token,
                                    .Index = Index,
                                    .Length = Token.Length
                                }
                            )
                    Order By T.Length Descending
                ).First
    
            Console.WriteLine("The longest string is '{0}' index is {1}",
                              Result.Word,
                              Result.Index)
        End Sub
    End Class
    

    While of course we can remedy that as shown below yet for simple operations such as this I see no merit. If the code was more complex and had to return a typed object we must use the second example below.

    'Option Infer Off
    Public Class Form1
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim Items As New List(Of String) From
            {
                "do you like tea",
                "Well that coffee was great",
                "interesting",
                "tea",
                "creame",
                "beep"
            }
            Dim Result As WhatEver =
                (
                    From T In Items _
                    .Select(Function(Token, Index) _
                                New WhatEver With
                                {
                                    .Word = Token,
                                    .Index = Index,
                                    .Length = Token.Length
                                }
                            )
                    Order By T.Length Descending
                ).FirstOrDefault
    
            If Result IsNot Nothing Then
                Console.WriteLine("The longest string is '{0}' index is {1}",
                                  Result.Word,
                                  Result.Index)
            End If
    
        End Sub
    End Class
    Public Class WhatEver
        Public Property Word As String
        Public Property Index As Integer
        Public Property Length As Integer
        Public Sub New()
        End Sub
    End Class
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my webpage under my profile but do not reply to forum questions.

    Sunday, July 5, 2015 1:50 AM
    Moderator
  • Kev,

    ... and only your second example is strongly-typed. In the absence of that, the compiler (and the CLR later) is doing a lot of guessing.

    Ok ok, "inferring", pardon me - and it's good at it, but still ... why do that?

    Answer: "Because it's easier". ;-)

    *****

    Don't infer types - in my opinion of course. :)


    Still lost in code, just at a little higher level.

    :-)

    Sunday, July 5, 2015 1:57 AM
  • Kev,

    ... and only your second example is strongly-typed. In the absence of that, the compiler (and the CLR later) is doing a lot of guessing.

    Ok ok, "inferring", pardon me - and it's good at it, but still ... why do that?

    Answer: "Because it's easier". ;-)

    *****

    Don't infer types - in my opinion of course. :)


    Still lost in code, just at a little higher level.

    :-)

    If you think I am doing it because it's easy then you missed the point.

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my webpage under my profile but do not reply to forum questions.

    Sunday, July 5, 2015 1:59 AM
    Moderator
  • If you think I am doing it because it's easy then you missed the point.

    It's not strongly-typed.

    *****

    You and I got into this debate last January with a post from Armin about anonymous types and LINQ-To-Object. You made good points, but I am of the belief that your code should never infer anything.

    Declare them on the front-end, even it's more cumbersome to do so.

    *****

    Obviously not everyone agrees. ;-)


    Still lost in code, just at a little higher level.

    :-)

    Sunday, July 5, 2015 2:05 AM
  • Frank,

     I also am a strong believer in using Option Strict and Explicit at all times.  I wish MS would just Turn them on by default and hide the options to turn them off.  From what i understand, it actually compiles quicker too, although it may not be enough to notice.  Not to mention that you can just look at the variables, parameters, and properties and tell what type they are suppose to be.

     I don`t know as much about it as you and Kevin but, i have had my options set like you have shown for several years now and i have never had to switch them for anything i ever programed.  Of coarse i don`t use LINQ much but, i never had to turn Infer off for the little bit i have.  When would you need to turn Infer off for using LINQ, i am curios ?


    If you say it can`t be done then i`ll try it

    Sunday, July 5, 2015 2:33 AM
  • I don`t know as much about it as you and Kevin but...

    Yea right, stop that - you know plenty!

    When would you need to turn Infer off for using LINQ, i am curios ?

    It depends on how "tight" you want it do be.

    In my opinion, infer nothing - the compiler has much less work to do and, equally important, so does everything that follows. Strongly-typed is, in my opinion (and clearly not everyone agrees) a way to ensure that the code isn't guessing at what you mean.

    Is it more work on our ends? Yes - I won't argue that point at all.


    Still lost in code, just at a little higher level.

    :-)

    Sunday, July 5, 2015 2:43 AM
  • Frank,

     I also am a strong believer in using Option Strict and Explicit at all times.  I wish MS would just Turn them on by default and hide the options to turn them off.  From what i understand, it actually compiles quicker too, although it may not be enough to notice.  Not to mention that you can just look at the variables, parameters, and properties and tell what type they are suppose to be.

     I don`t know as much about it as you and Kevin but, i have had my options set like you have shown for several years now and i have never had to switch them for anything i ever programed.  Of coarse i don`t use LINQ much but, i never had to turn Infer off for the little bit i have.  When would you need to turn Infer off for using LINQ, i am curios ?


    If you say it can`t be done then i`ll try it

    Ok, you asked about LINQ so let's do LINQ. ;-)

    Compare these two:

    Option Strict Off Option Explicit Off Option Infer On Imports System.IO Public Class Form1 Private Sub Form1_Load(sender As System.Object, _ e As System.EventArgs) _ Handles MyBase.Load Const dir = "K:\Personal Folders\Jessica" Dim collection1 = _ From something In Directory.EnumerateFiles(dir) Dim collection2 = _ From something In Directory.EnumerateFiles(dir) _ Order By something Stop End Sub End Class


    ... and with a more strict control:

    Option Strict On Option Explicit On Option Infer Off Imports System.IO Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Load Const dir As String = "K:\Personal Folders\Jessica" Dim collection1 As System.Collections.Generic.IEnumerable(Of String) = _ From something As String In Directory.EnumerateFiles(dir) Dim collection2 As System.Linq.IOrderedEnumerable(Of String) = _ From something As String In Directory.EnumerateFiles(dir) _ Order By something Stop End Sub End Class


    Is one better than the other?

    I'll let you decide that for yourself - but the second one isn't using type inference in any way. It knows what it is because you told it so.

    :)


    Still lost in code, just at a little higher level.

    :-)

    Sunday, July 5, 2015 2:53 AM
  •  Sorry, i see i mistyped that in my last post.  I actually keep Infer off but, i know i have heard some people say you need to turn it on for using LINQ sometimes.  I just did not understand why because i never turned it on and i have never had a problem with using LINQ.  I figured maybe there was some special circumstances that you needed to turn it on.  I guess i was understanding it wrong.  Thanks Frank.   8)


    If you say it can`t be done then i`ll try it

    Sunday, July 5, 2015 3:05 AM
  •  Sorry, i see i mistyped that in my last post.  I actually keep Infer off but, i know i have heard some people say you need to turn it on for using LINQ sometimes.  I just did not understand why because i never turned it on and i have never had a problem with using LINQ.  I figured maybe there was some special circumstances that you needed to turn it on.  I guess i was understanding it wrong.  Thanks Frank.   8)


    If you say it can`t be done then i`ll try it

    Then here's a better example:

    Option Strict Off Option Explicit Off Option Infer On Imports System.IO Public Class Form1 Private Sub Form1_Load(sender As System.Object, _ e As System.EventArgs) _ Handles MyBase.Load Const dir = "K:\Personal Folders\Jessica" Dim collection1 = _ From something In Directory.EnumerateFiles(dir) _ Select New With {.StringLength = something.Length} 'Dim collection2 = _ ' From something In Directory.EnumerateFiles(dir) _ ' Order By something Stop End Sub End Class


    Ok, a dumb example - but that one is using an anonymous type (as Kevin was talking about).

    You can't do that with the other settings - it will insist that you tell it what the type is - and you can't define that (because it's an anonymous type - a "make it up as it goes" class).


    Still lost in code, just at a little higher level.

    :-)

    Sunday, July 5, 2015 3:13 AM
  • Ok,  i think i understand it a little better now.  Thanks for taking the time to throw the examples together Frank.  I always understand things better by seeing examples instead of just reading about them.   Thanks again Frank.   Have a good night, i am getting off here for tonight.   8)

    If you say it can`t be done then i`ll try it

    Sunday, July 5, 2015 3:39 AM
  • Kev,

    ... yea, but you know how I feel about anonymous types! ;-)


    Still lost in code, just at a little higher level.

    :-)

    Is that sarcasm? ;)  I know how I feel, why doesn't Microsoft create an Anonymous type so I can write

            Dim foo As Anonymous = New With {.Name = "paperclips", .Price = 1.29}


    'Those who use Application.DoEvents() have no idea what it does and those who know what it does never use it.'  JohnWein

    Multics

    My Serial Port Answer

    Sunday, July 5, 2015 11:11 AM
  • ...why doesn't Microsoft create an Anonymous type so I can write

            Dim foo As Anonymous = New With {.Name = "paperclips", .Price = 1.29}

    It would be nice for convenience, sure, but it would still suffer from the same thing that I think is a bad idea: Type inference.

    Obviously everyone doesn't agree; in fact, I dare say that most vehemently disagree! ;-)


    Still lost in code, just at a little higher level.

    :-)

    Sunday, July 5, 2015 1:18 PM