Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. c# var

c# var

Scheduled Pinned Locked Moved The Lounge
questioncsharplounge
60 Posts 37 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • Z ZurdoDev

    What is the love affair with var? I see sample code where they do something like

    var url = "http://someapi";

    This feels lazy to me but I am open minded and am curious if I am missing something. Is there some benefit to declaring most things var instead of what they actually are? In the case above, a string.

    Social Media - A platform that makes it easier for the crazies to find each other. Everyone is born right handed. Only the strongest overcome it. Fight for left-handed rights and hand equality.

    M Offline
    M Offline
    Michael Waters
    wrote on last edited by
    #47

    I (almost) only use var for non-production code, when I'm writing from whole cloth and doing initial diagnostics. As the code matures, I replace (almost) all instances of var with the actual types. Great way to force you to review and refactor before release. For very long types, I'll use var, but only when the type is already included in the same location, like a declaration and instantiation.

    1 Reply Last reply
    0
    • Z ZurdoDev

      What is the love affair with var? I see sample code where they do something like

      var url = "http://someapi";

      This feels lazy to me but I am open minded and am curious if I am missing something. Is there some benefit to declaring most things var instead of what they actually are? In the case above, a string.

      Social Media - A platform that makes it easier for the crazies to find each other. Everyone is born right handed. Only the strongest overcome it. Fight for left-handed rights and hand equality.

      D Offline
      D Offline
      Davyd McColl
      wrote on last edited by
      #48

      Apart from the obvious (it saves typing and you have a set maximum number of keystrokes you can make in your life), it also allows for alignment which makes things easier to read (we're better with vertical scanning than horizontal scanning - for more see: https://www.youtube.com/watch?v=ZsHMHukIlJY and also there's just plain less to read!) but also because consuming code is more likely to survive a refactor intact: changing return type to something with similar shape means no consumer changes, renames of classes don't have to alter as many lines of code. Since it's syntactic sugar, it costs nothing at runtime and it's normally one of the first automated fixes I do in a file when I enter legacy code.

      ------------------------------------------------ If you say that getting the money is the most important thing You will spend your life completely wasting your time You will be doing things you don't like doing In order to go on living That is, to go on doing things you don't like doing Which is stupid. - Alan Watts https://www.youtube.com/watch?v=-gXTZM\_uPMY

      1 Reply Last reply
      0
      • Z ZurdoDev

        What is the love affair with var? I see sample code where they do something like

        var url = "http://someapi";

        This feels lazy to me but I am open minded and am curious if I am missing something. Is there some benefit to declaring most things var instead of what they actually are? In the case above, a string.

        Social Media - A platform that makes it easier for the crazies to find each other. Everyone is born right handed. Only the strongest overcome it. Fight for left-handed rights and hand equality.

        S Offline
        S Offline
        salz150
        wrote on last edited by
        #49

        I've read that convention is to use "var" when the type of variable is apparent by reading the code. If you printed out this code it would still be pretty obvious that "url" is a string. If you can't tell the type by reading the code then the actual type should be used. It is lazy but if it eliminates some redundancy and makes coding a little quicker than it's a good thing. I personally follow the convention above but I know some people use var for everything.

        1 Reply Last reply
        0
        • Z ZurdoDev

          What is the love affair with var? I see sample code where they do something like

          var url = "http://someapi";

          This feels lazy to me but I am open minded and am curious if I am missing something. Is there some benefit to declaring most things var instead of what they actually are? In the case above, a string.

          Social Media - A platform that makes it easier for the crazies to find each other. Everyone is born right handed. Only the strongest overcome it. Fight for left-handed rights and hand equality.

          U Offline
          U Offline
          User 2893688
          wrote on last edited by
          #50

          Actually your example is quite interesting, as it isn't really a String but rather Uri. The correct way to declare it would have been

          using System;

          ...
          Uri url = new Uri("http://www.contoso.com/");

          WebRequest wr = WebRequest.Create(siteUri);

          But as you might have figured, you could have just used this instead

          var url = new Uri("http://www.contoso.com/");

          var wr = WebRequest.Create(siteUri);

          or just

          var url = "http:// www. contoso.com/";
          var request = WebRequest.Create (url);

          Z 1 Reply Last reply
          0
          • U User 2893688

            Actually your example is quite interesting, as it isn't really a String but rather Uri. The correct way to declare it would have been

            using System;

            ...
            Uri url = new Uri("http://www.contoso.com/");

            WebRequest wr = WebRequest.Create(siteUri);

            But as you might have figured, you could have just used this instead

            var url = new Uri("http://www.contoso.com/");

            var wr = WebRequest.Create(siteUri);

            or just

            var url = "http:// www. contoso.com/";
            var request = WebRequest.Create (url);

            Z Offline
            Z Offline
            ZurdoDev
            wrote on last edited by
            #51

            Member 2896020 wrote:

            var url = "http:// www. contoso.com/"; var request = WebRequest.Create (url);

            Which is essentially what it was. But url is a string. I don't see the value in typing var instead of string.

            Social Media - A platform that makes it easier for the crazies to find each other. Everyone is born right handed. Only the strongest overcome it. Fight for left-handed rights and hand equality.

            1 Reply Last reply
            0
            • Sander RosselS Sander Rossel

              VB doesn't have var? :confused: The equivalent would be:

              Dim something = "my string"

              Which looks fine to me and is still strongly typed, unless Options Strict is Off.

              Mycroft Holmes wrote:

              As for var content changing type and not having to refactor

              Using var is strongly typed so I don't really get what you're saying. Are you thinking of dynamic or Option Strict Off (which luckily DOESN'T have an equivalent in C# X| )?

              Best, Sander sanderrossel.com Migrating Applications to the Cloud with Azure arrgh.js - Bringing LINQ to JavaScript Object-Oriented Programming in C# Succinctly

              M Offline
              M Offline
              Mycroft Holmes
              wrote on last edited by
              #52

              I use c# and almost never use var, and the content changing comment was a response to some of the previous posts.

              Never underestimate the power of human stupidity - RAH I'm old. I know stuff - JSOP

              1 Reply Last reply
              0
              • OriginalGriffO OriginalGriff

                I'd actually prefer it is you could do this:

                Dictionary> complicatedDictionary = new *();

                To me, that would be a more natural way of showing what the type of complicatedDictionary actually is. As it is, I find var is mainly over used by the lazy-and-don't-care script kiddies ...

                "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony AntiTwitter: @DalekDave is now a follower!

                F Offline
                F Offline
                Fabio Franco
                wrote on last edited by
                #53

                C# 9.0 will have it: [Welcome to C# 9.0 | .NET Blog](https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/#target-typed-new-expressions)

                To alcohol! The cause of, and solution to, all of life's problems - Homer Simpson ---- Our heads are round so our thoughts can change direction - Francis Picabia

                1 Reply Last reply
                0
                • Z ZurdoDev

                  What is the love affair with var? I see sample code where they do something like

                  var url = "http://someapi";

                  This feels lazy to me but I am open minded and am curious if I am missing something. Is there some benefit to declaring most things var instead of what they actually are? In the case above, a string.

                  Social Media - A platform that makes it easier for the crazies to find each other. Everyone is born right handed. Only the strongest overcome it. Fight for left-handed rights and hand equality.

                  F Offline
                  F Offline
                  Fabio Franco
                  wrote on last edited by
                  #54

                  The problem is that it sometimes becomes a style guideline in teams. I have seen that happening before, which is just stupid to me. "Oh, but you can just hover over it and you will see". This mindset can be a real nightmare on code reviews. I hate the laziness that motivated most var uses I have seen. People don't even know why var was created (to support anonymous types). There are though, as some people have already mentioned, some situations where var makes the code cleaner. But I actually never seen that kind of diligence, so wherever I could I abolished the used of var for non anonymous types. To make matters worse, stupid resharper (that some people like to use) has the default setting that everything should be var. So it pretty much converts the new-comers to the var mindset from the start.

                  To alcohol! The cause of, and solution to, all of life's problems - Homer Simpson ---- Our heads are round so our thoughts can change direction - Francis Picabia

                  1 Reply Last reply
                  0
                  • Z ZurdoDev

                    What is the love affair with var? I see sample code where they do something like

                    var url = "http://someapi";

                    This feels lazy to me but I am open minded and am curious if I am missing something. Is there some benefit to declaring most things var instead of what they actually are? In the case above, a string.

                    Social Media - A platform that makes it easier for the crazies to find each other. Everyone is born right handed. Only the strongest overcome it. Fight for left-handed rights and hand equality.

                    Z Offline
                    Z Offline
                    zezba9000
                    wrote on last edited by
                    #55

                    For primitive types I like to say what they're BUT var should be used for most other types. For example

                    var myGeneric = new List>>();

                    VS

                    List>> myGeneric = new List>>();

                    Both are the same but one much easier to read.

                    1 Reply Last reply
                    0
                    • OriginalGriffO OriginalGriff

                      I'd actually prefer it is you could do this:

                      Dictionary> complicatedDictionary = new *();

                      To me, that would be a more natural way of showing what the type of complicatedDictionary actually is. As it is, I find var is mainly over used by the lazy-and-don't-care script kiddies ...

                      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony AntiTwitter: @DalekDave is now a follower!

                      D Offline
                      D Offline
                      David On Life
                      wrote on last edited by
                      #56

                      Dictionary> complicatedDictionary = new ();

                      Is on the planned list for C# 9.0.

                      1 Reply Last reply
                      0
                      • Z ZurdoDev

                        What is the love affair with var? I see sample code where they do something like

                        var url = "http://someapi";

                        This feels lazy to me but I am open minded and am curious if I am missing something. Is there some benefit to declaring most things var instead of what they actually are? In the case above, a string.

                        Social Media - A platform that makes it easier for the crazies to find each other. Everyone is born right handed. Only the strongest overcome it. Fight for left-handed rights and hand equality.

                        K Offline
                        K Offline
                        KateAshman
                        wrote on last edited by
                        #57

                        In my experience, the need to use var arises from wanting to hide the sometimes lengthy names of collection iterators in foreach declarations. Especially when Linq is used to get the collection, the declaration can become messy. But you now how it goes: first it's to shorten lengthy iterator names, then lengthy class names, then pretty much everywhere because it looks more consistent for some people. I can support the use in foreach declarations, but everywhere else it's more of an annoyance. I never understood the desire to hide stuff like this. It's like an unspoken commitment to never refactor whatever is hidden. On a related note: Regions. Why?

                        1 Reply Last reply
                        0
                        • Z ZurdoDev

                          What is the love affair with var? I see sample code where they do something like

                          var url = "http://someapi";

                          This feels lazy to me but I am open minded and am curious if I am missing something. Is there some benefit to declaring most things var instead of what they actually are? In the case above, a string.

                          Social Media - A platform that makes it easier for the crazies to find each other. Everyone is born right handed. Only the strongest overcome it. Fight for left-handed rights and hand equality.

                          J Offline
                          J Offline
                          JohaViss61
                          wrote on last edited by
                          #58

                          I really like the short notation. When I need to know what type the variable is, I hover the mouse cursor over it and it will show the actual type. And so long as I am not paid by the character, I will use the shortest notation I can use.:cool:

                          1 Reply Last reply
                          0
                          • Z ZurdoDev

                            What is the love affair with var? I see sample code where they do something like

                            var url = "http://someapi";

                            This feels lazy to me but I am open minded and am curious if I am missing something. Is there some benefit to declaring most things var instead of what they actually are? In the case above, a string.

                            Social Media - A platform that makes it easier for the crazies to find each other. Everyone is born right handed. Only the strongest overcome it. Fight for left-handed rights and hand equality.

                            B Offline
                            B Offline
                            BDieser
                            wrote on last edited by
                            #59

                            Resharper encourages var use for whatever reason. However, it does show what the actual type is.

                            1 Reply Last reply
                            0
                            • Z ZurdoDev

                              What is the love affair with var? I see sample code where they do something like

                              var url = "http://someapi";

                              This feels lazy to me but I am open minded and am curious if I am missing something. Is there some benefit to declaring most things var instead of what they actually are? In the case above, a string.

                              Social Media - A platform that makes it easier for the crazies to find each other. Everyone is born right handed. Only the strongest overcome it. Fight for left-handed rights and hand equality.

                              U Offline
                              U Offline
                              User 14060113
                              wrote on last edited by
                              #60

                              There is no advantage. If you just write a scribble, then always using var is Ok. But if you write production-level code, var is sloppy style and thus an absolute no-go. Before IntelliSense was able to automatically convert the var's in your source code to the correct type, var was even an evidence of a programmer not knowing what type they're using. Only exception: Use var to avoid writing the same type twice in the same line. Bad

                              List list = new List();

                              Good

                              var list = new List();

                              Because then, when you want to change the type, let's say from List to HashSet, you only have to change it once. IntelliSense also suggests this, at least in VS 2017.

                              1 Reply Last reply
                              0
                              Reply
                              • Reply as topic
                              Log in to reply
                              • Oldest to Newest
                              • Newest to Oldest
                              • Most Votes


                              • Login

                              • Don't have an account? Register

                              • Login or register to search.
                              • First post
                                Last post
                              0
                              • Categories
                              • Recent
                              • Tags
                              • Popular
                              • World
                              • Users
                              • Groups