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.
  • M Mircea Neacsu

    You are going on a dangerous path. It leads you to the days when an insignificant dot was significant:

    auto i = 2;
    auto j = 3;
    auto k = i/j;
    auto f = 2./j;
    // f != k
    // any similarity with FORTRAN is intentional

    Besides "auto" has four letters and "int" has three; it's not energy efficient :)

    Mircea

    Greg UtasG Offline
    Greg UtasG Offline
    Greg Utas
    wrote on last edited by
    #34

    Not very dangerous unless one ignores compiler warnings. Then again, I don't use floating point very often. The main one I have to watch for is

    for(auto i = 0...

    which makes i an int when what might actually be called for is a size_t.

    Robust Services Core | Software Techniques for Lemmings | Articles

    <p><a href="https://github.com/GregUtas/robust-services-core/blob/master/README.md">Robust Services Core</a>
    <em>The fox knows many things, but the hedgehog knows one big thing.</em></p>

    1 Reply Last reply
    0
    • Z ZurdoDev

      Yes, it was 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
      MadMyche
      wrote on last edited by
      #35

      But what if you meant it as a URI? I think SQL would call this ambiguous

      Director of Transmogrification Services Shinobi of Query Language Master of Yoda Conditional

      Z 1 Reply Last reply
      0
      • M MadMyche

        But what if you meant it as a URI? I think SQL would call this ambiguous

        Director of Transmogrification Services Shinobi of Query Language Master of Yoda Conditional

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

        MadMyche wrote:

        But what if you meant it as a URI?

        Then you do new Uri(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
        • 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
          Mycroft Holmes
          wrote on last edited by
          #37

          When I moved from VB (where purists dump on var from a great height) to c# where explicit types were mandatory I lost all faith in var, it became the one thing in VB that I loathed. Now that it has phoenixed in c# I refuse to use it. As for var content changing type and not having to refactor, what a croc of shit, you should HAVE to refactor if you change type or at least check your usage of the variable.

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

          Sander RosselS 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!

            pkfoxP Offline
            pkfoxP Offline
            pkfox
            wrote on last edited by
            #38

            Yes I agree

            "We can't stop here - this is bat country" - Hunter S Thompson - RIP

            1 Reply Last reply
            0
            • OriginalGriffO OriginalGriff

              The problem with that is that you are working to what should have been a breaking change. And that's important, because if you were assuming int division as a result of the original type spec for example, then a breaking change means you know it's just failed and can adapt to it. var in that case means you don't know, and output can be subtly wrong and unnoticed until it's a real problem. I'd say var should be there for temporary storage of Linq results, and nowhere else ...

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

              pkfoxP Offline
              pkfoxP Offline
              pkfox
              wrote on last edited by
              #39

              :thumbsup::thumbsup::thumbsup:

              "We can't stop here - this is bat country" - Hunter S Thompson - RIP

              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.

                Sander RosselS Offline
                Sander RosselS Offline
                Sander Rossel
                wrote on last edited by
                #40

                I use var almost exclusively these days. I started out using it sometimes, but then I started using it more and more. To me, it just seems nice to have all my vars lined up nicely :D Some people thing the var keyword isn't strongly typed, but it is (we have dynamic for that). It's not like JavaScript's var keyword. It's only absolutely necessary to use var when working with anonymous types (still strongly typed!).

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

                1 Reply Last reply
                0
                • M Mycroft Holmes

                  When I moved from VB (where purists dump on var from a great height) to c# where explicit types were mandatory I lost all faith in var, it became the one thing in VB that I loathed. Now that it has phoenixed in c# I refuse to use it. As for var content changing type and not having to refactor, what a croc of shit, you should HAVE to refactor if you change type or at least check your usage of the variable.

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

                  Sander RosselS Offline
                  Sander RosselS Offline
                  Sander Rossel
                  wrote on last edited by
                  #41

                  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 1 Reply Last reply
                  0
                  • G GuyThiebaut

                    The advantage of var is if "http://someapi" was a variable or class instance instead of a string literal and you changed its type, you would not then need to refactor the code elsewhere. In your example it's just a case of habit probably, however it's obvious from what is on the right that it's a string. It can sometimes make it harder to debug issues as jumping to the class definition might not always be supported in the IDE you use to debug the var url value with or have to wait for the IDE to resolve the type that the var is. That's my take on var...

                    “That which can be asserted without evidence, can be dismissed without evidence.”

                    ― Christopher Hitchens

                    B Offline
                    B Offline
                    BillWoodruff
                    wrote on last edited by
                    #42

                    GuyThiebaut wrote:

                    The advantage of var is if "http://someapi" was a variable or class instance instead of a string literal and you changed its type, you would not then need to refactor the code elsewhere.

                    "O, that way madness lies; let me shun that!" (King Lear)

                    «One day it will have to be officially admitted that what we have christened reality is an even greater illusion than the world of dreams.» Salvador Dali

                    G 1 Reply Last reply
                    0
                    • M Marc Clifton

                      OriginalGriff wrote:

                      that would be a more natural way of showing what the type

                      Yup. And as I replied on the Insider News, what I really want is: var foo = new(); In most cases, the compiler should be able to figure out what foo is by inspecting its usage in the code! :laugh:

                      Latest Articles:
                      Abusing Extension Methods, Null Continuation, and Null Coalescence Operators

                      B Offline
                      B Offline
                      BillWoodruff
                      wrote on last edited by
                      #43

                      Marc Clifton wrote:

                      In most cases, the compiler should be able to figure out what foo is by inspecting its usage in the code!

                      If you turn the compiler into a psychic, be prepared for bad news :wtf:

                      «One day it will have to be officially admitted that what we have christened reality is an even greater illusion than the world of dreams.» Salvador Dali

                      1 Reply Last reply
                      0
                      • B BillWoodruff

                        GuyThiebaut wrote:

                        The advantage of var is if "http://someapi" was a variable or class instance instead of a string literal and you changed its type, you would not then need to refactor the code elsewhere.

                        "O, that way madness lies; let me shun that!" (King Lear)

                        «One day it will have to be officially admitted that what we have christened reality is an even greater illusion than the world of dreams.» Salvador Dali

                        G Offline
                        G Offline
                        GuyThiebaut
                        wrote on last edited by
                        #44

                        Tell me about it, I have been coding in Kotlin for an Android application and in Kotlin pretty much every type is inferred. So the code is peppered with it when referring to a property and it can be pretty much anything.

                        “That which can be asserted without evidence, can be dismissed without evidence.”

                        ― Christopher Hitchens

                        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
                          Steve Naidamast
                          wrote on last edited by
                          #45

                          The C# "var" construct and other such constructs in both C# and VB.NET are merely short-cuts or the usage of system defaults. This makes for very ambiguous code over the length of an application's development. This is why I don't even use the generic list-type and still use array-lists instead. Despite the slight performance decreases (which most will not notice since such constructs often do not contain thousands of objects or items in general), having easy to read strongly typed code makes my applications much more easily maintainable.

                          Steve Naidamast Sr. Software Engineer Black Falcon Software, Inc. blackfalconsoftware@outlook.com

                          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.

                            R Offline
                            R Offline
                            Rusty Bullet
                            wrote on last edited by
                            #46

                            The last place I worked would fail you in code reviews if you did not use var. Their (ill) logic was something to do with a design pattern, and when Entity Framework would cough on var, they added lines of code to get it to pass instead of just using the correct type.

                            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.

                              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
                                          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