Results 1 to 9 of 9

Thread: fundamental question about Option Infer Off

  1. #1

    Thread Starter
    PowerPoster
    Join Date
    Feb 2016
    Location
    Tennessee
    Posts
    2,437

    fundamental question about Option Infer Off

    I'm looking at some code I found on the net and because I have Option Infer OFF, the compiler is screaming at me, lol. Here is the code:
    Code:
       Private Shared Function GetSystemUpTimeInfo() As String
            Try
                Dim time = GetSystemUpTime()
                Dim upTime = String.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms", time.Hours, time.Minutes, time.Seconds, time.Milliseconds)
                Return String.Format("{0}", upTime)
            Catch ex As Exception
                'handle the exception your way
                Return String.Empty
            End Try
        End Function
    
        Private Shared Function GetSystemUpTime() As TimeSpan
            Try
                Dim uptime = New PerformanceCounter("System", "System Up Time")
                uptime.NextValue
                Return TimeSpan.FromSeconds(uptime.NextValue)
            Catch ex As Exception
                'handle the exception your way
                Return New TimeSpan(0, 0, 0, 0)
            End Try
        End Function
    Here are the exact items that the compiler doesn't like:

    Code:
    Dim time = GetSystemUpTime()
                Dim upTime = String.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms", time.Hours, time.Minutes, time.Seconds, time.Milliseconds)
    And
    Code:
      Dim uptime = New PerformanceCounter("System", "System Up Time")
                uptime.NextValue
                Return TimeSpan.FromSeconds(uptime.NextValue)
    How do I declare these variables where the compiler won't complain?

    thanks

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,299

    Re: fundamental question about Option Infer Off

    Option Infer On simply lets you omit the type of the variable from the declaration where that type can be inferred from the expression used to initialise that variable. In this case:
    vb.net Code:
    1. Dim time = GetSystemUpTime()
    the expression used to initialise the 'time' variable is a call to the GetSystemUpTime. The return type of that method is TimeSpan so the compiler can infer that the type of the 'time' variable is TimeSpan. If you have Option Infer Off then that type inference cannot occur, so you have to declare that 'time' is type TimeSpan explicitly:
    vb.net Code:
    1. Dim time As TimeSpan = GetSystemUpTime()
    Type inference is simply a convenience in cases like this. If you always declare your variables types explicitly then you don't need type inference. The reason that it was added is that it is essential when using anonymous types, which are a feature of LINQ. You cannot declare a variable as an anonymous type so it MUST be inferred from the initialising expression. If you don't use anonymous types anywhere then you can set Option Infer Off and simply do as you would have been doing previously and specify the type of every variable.

  3. #3

    Thread Starter
    PowerPoster
    Join Date
    Feb 2016
    Location
    Tennessee
    Posts
    2,437

    Re: fundamental question about Option Infer Off

    Thank you. Great answer. If I'm understanding what you are saying, it's not really a bad thing. I still have strict and Explicit on...

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,299

    Re: fundamental question about Option Infer Off

    Quote Originally Posted by jumper77 View Post
    If I'm understanding what you are saying, it's not really a bad thing.
    Correct. If you have Option Explicit Off or Option Strict Off then you allow yourself to write code that is less explicit where typing is concerned but having Option Infer Off means that you must write code that is more explicit.

  5. #5

    Thread Starter
    PowerPoster
    Join Date
    Feb 2016
    Location
    Tennessee
    Posts
    2,437

    Re: fundamental question about Option Infer Off

    Thank you for explaining all of that. When I was doing this for a living, I didn't have to worry about this kind of stuff for some reason. I think it's because we were just writing good code at the start of it all.

    I only come across these issues with code I've got off the Internet, lol

  6. #6
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,578

    Re: fundamental question about Option Infer Off

    Infer is an option that, as you progress on your programming journey, you eventually choose to turn on. At the start, it's very helpful to make sure you're always matching types to the right variables. Later, it turns out you don't make those kinds of mistakes as often and, when you're in the situations where it's easier to make them, you pay more attention.

    The idea is "I return something that's not a TimeSpan from a method like GetSystemUptime() about 100,000 times less than I ever want to type 'Dim groups As IEnumerable(Of IGrouping(Of String, Tuple(String, Int, List(Of Integer), String))) = <some LINQ query>'".

    In short, LINQ and lambda methods created the need, using them without Option Infer is dreadfully tedious and requires you to memorize a lot more. But if you aren't using those yet, Option Infer Off is a great safety net against some easy mistakes.
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

  7. #7
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,299

    Re: fundamental question about Option Infer Off

    When Option Infer was first introduced, I started out deciding that I was only going to take advantage when it was 100% obvious what the type was, e.g. I would declare a String variable without specifying the type only if it was initialised with a call to ToString or comparable. It wasn't long before that went out the window and I use let variable types be inferred pretty much any time they can now.

    Given that you can mouse over a variable in VS to see what type it is and the same goes for an initialising expression, I don't really see the point in doing otherwise. If I write code examples to post here or the like then I'll specify types explicitly if it's not obvious from usage but any code I write for work or personal projects is pretty much guaranteed to be viewed in VS.

  8. #8
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,578

    Re: fundamental question about Option Infer Off

    Yeah, it's sort of how I felt when I started using JavaScript and why sometimes I feel like adding on junk like TypeScript to it is too much effort. (I'm not arguing with JMC here, I'm trying to provide some clarity for other readers.)

    Option Infer is less about mistakes and more about clarity. This line is super obvious and leaving out the type isn't going to confuse anyone:
    Code:
    Dim numberOfApples = 3
    The next-most complex way to express it isn't really that much worse:
    Code:
    Dim numberOfApples = appleBasket.Count()
    You don't need much experience to see "number of apples" and think "whole number". This is further confirmed by seeing a call to Count(), which returns an Integer. It just doesn't make any sense for "the number of items in a collection" to be fractional or a String or something else.

    But that IS confusing to very new programmers. They haven't ingrained those practices. The line is obvious to me because I always name my variables "numberOfX" to imply they are whole numbers. I did this so I can stop thinking about whether "apples" refers to a number or an array or other collection. I name dictionaries "xxxLookup" so I can more easily remember they aren't arrays. I put "Queue" or "List" on the end of a name if I feel there's any POSSIBLE confusion.

    I started adopting those practices because even when Option Infer didn't exist, it was a pain in the butt to have to try to remember what type certain variables were. Following these practices 100% of the time probably saves me at least a few hours per month!

    That's why I use Option Infer extensively. I developed a methodology and discipline that makes it very hard for me to make subtle type mistakes. It also helps that I tend to favor architectures with "very many" "very small" classes with "very few" "very small" methods. I used quotes because that's a kind of fill-in-the-blanks for coding style.

    Most newbies, and honestly most people, use a style that has "very few" "very large" classes with "very many" "very large" methods. That tends to be the situation where it's much harder to keep track of what this or that method returns, and in those situations you don't want to be using Option Infer.

    I think it's true that "most experts like Option Infer on", but I don't think it's true that "you will learn to write better code with Option Infer on". I think new programmers should use Option Infer until they start saying things to themselves like, "Gee, I never really get confused about what type something should be, I wonder if I can do well with Option Infer off?" Then you try it. And life either gets better or worse. If it gets worse, you turn it back on. The right setting is the one that helps you write error-free code as quickly as possible.
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

  9. #9

    Thread Starter
    PowerPoster
    Join Date
    Feb 2016
    Location
    Tennessee
    Posts
    2,437

    Re: fundamental question about Option Infer Off

    Thank you both for the discussion on this topic. I find it very interesting. I hope some of the readers of this thread enjoy the talk as much as I. And Sitten, there was a time when I was guilty of making classes or subs way too big, but later found out like you said, it's much harder to keep track of what's going on. So these days I prefer breaking things up into smaller methods. I'm much happier with that.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width