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

    ZurdoDev wrote:

    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.

    I felt the same way initially, and I agree, for something simple like a native type, I rarely use var. However: var complicatedDictionary = new Dictionary>(); and worse, I like definitely like it.

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

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

    Marc Clifton wrote:

    var complicatedDictionary = new Dictionary<SomeKey, List<KeyValue>>(); and worse, I like definitely like it.

    I can see that.

    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
    • M Marc Clifton

      ZurdoDev wrote:

      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.

      I felt the same way initially, and I agree, for something simple like a native type, I rarely use var. However: var complicatedDictionary = new Dictionary>(); and worse, I like definitely like it.

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

      OriginalGriffO Offline
      OriginalGriffO Offline
      OriginalGriff
      wrote on last edited by
      #8

      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!

      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
      "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

      O Richard DeemingR M N pkfoxP 7 Replies Last reply
      0
      • S Slacker007

        it is good for a lot of applications but can be missused very easily. it's main purpose is code readability.

        MyMostExcellentBaseClassOfAllClassesInTheWholeWorld myClass = new MyMostExcellentBaseClassOfAllClassesInTheWholeWorld();

        or

        var myClass = new MyMostExcellentBaseClassOfAllClassesInTheWholeWorld();

        It is really good when working with Linq, etc. as well.

        OriginalGriffO Offline
        OriginalGriffO Offline
        OriginalGriff
        wrote on last edited by
        #9

        I'd rather see it as:

        MyMostExcellentBaseClassOfAllClassesInTheWholeWorld myClass = new *();

        If that was possible.

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

        "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
        "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

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

          L Offline
          L Offline
          Lost User
          wrote on last edited by
          #10

          var is ok as long as I can have a look to the code in VS with the help of intelisense. But in case I study a code snippet on www it becomes simply horrible because the real type is something hidden :(

          It does not solve my Problem, but it answers my question

          1 Reply Last reply
          0
          • OriginalGriffO OriginalGriff

            I'd rather see it as:

            MyMostExcellentBaseClassOfAllClassesInTheWholeWorld myClass = new *();

            If that was possible.

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

            J Offline
            J Offline
            Johnny J
            wrote on last edited by
            #11

            I think you can find instructions on how to create your own programming language here on CP, actually... ;P

            Anything that is unrelated to elephants is irrelephant
            Anonymous
            -----
            The problem with quotes on the internet is that you can never tell if they're genuine
            Winston Churchill, 1944
            -----
            Never argue with a fool. Onlookers may not be able to tell the difference.
            Mark Twain

            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.

              O Offline
              O Offline
              obermd
              wrote on last edited by
              #12

              As far as I can tell most uses of "var" are sheer laziness. The only time I var useful is when I need to store the results of a LINQ expression for later processing.

              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

                O Offline
                O Offline
                obermd
                wrote on last edited by
                #13

                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.

                Absolutely not true. Changing a data type and then attempting to use it elsewhere is guaranteed to cause you to have to modify code everywhere it's used. Fortunately the VS IDE is smart enough to identify those spots for you.

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

                  O Offline
                  O Offline
                  obermd
                  wrote on last edited by
                  #14

                  This is one place where VB has a better syntax:

                  dim complicatedDictionary as New Dictionary(of SomeKey, List(KeyValue))

                  I'd prefer to see the < and > symbols used around the type information as this would make it clear what is type information vs. New parameters/arguments.

                  1 Reply Last reply
                  0
                  • O obermd

                    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.

                    Absolutely not true. Changing a data type and then attempting to use it elsewhere is guaranteed to cause you to have to modify code everywhere it's used. Fortunately the VS IDE is smart enough to identify those spots for you.

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

                    obermd wrote:

                    Absolutely not true. Changing a data type and then attempting to use it elsewhere is guaranteed to cause you to have to modify code everywhere it's used.

                    Even when changing from a short to a long?

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

                      W Offline
                      W Offline
                      Wendelius
                      wrote on last edited by
                      #16

                      I rarely use var but I do use it when returning a tuple from a method to avoid out parameters. For example

                      void MainMethod() {
                      ...
                      var methodCall = SomeMethod();
                      if (!methodCall.Success) {
                      return;
                      }
                      ...
                      }

                      (bool Success, int? ReturnValue) SomeMethod() {
                      int? retValue;

                      ...
                      if (...) {
                      return (Success: false, ReturnValue: null);
                      }
                      ...

                      return (Success: true, ReturnValue: retValue):
                      }

                      Richard DeemingR 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!

                        Richard DeemingR Offline
                        Richard DeemingR Offline
                        Richard Deeming
                        wrote on last edited by
                        #17

                        That should hopefully be coming in C# 9: csharplang/target-typed-new.md at master · dotnet/csharplang · GitHub[^] Champion "Target-typed `new` expression" · Issue #100 · dotnet/csharplang · GitHub[^] Edit: As already mentioned in the Insider News[^]. :)


                        "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                        "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                        OriginalGriffO 1 Reply Last reply
                        0
                        • W Wendelius

                          I rarely use var but I do use it when returning a tuple from a method to avoid out parameters. For example

                          void MainMethod() {
                          ...
                          var methodCall = SomeMethod();
                          if (!methodCall.Success) {
                          return;
                          }
                          ...
                          }

                          (bool Success, int? ReturnValue) SomeMethod() {
                          int? retValue;

                          ...
                          if (...) {
                          return (Success: false, ReturnValue: null);
                          }
                          ...

                          return (Success: true, ReturnValue: retValue):
                          }

                          Richard DeemingR Offline
                          Richard DeemingR Offline
                          Richard Deeming
                          wrote on last edited by
                          #18

                          Or better yet:

                          var (Success, ReturnValue) = SomeMethod();
                          if (!Success) {
                          return;
                          }


                          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                          "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                          1 Reply Last reply
                          0
                          • Richard DeemingR Richard Deeming

                            That should hopefully be coming in C# 9: csharplang/target-typed-new.md at master · dotnet/csharplang · GitHub[^] Champion "Target-typed `new` expression" · Issue #100 · dotnet/csharplang · GitHub[^] Edit: As already mentioned in the Insider News[^]. :)


                            "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                            OriginalGriffO Offline
                            OriginalGriffO Offline
                            OriginalGriff
                            wrote on last edited by
                            #19

                            Hah! I just spent half an hour trying to persuade Google to let me know how you make suggestions for the C# spec ... :laugh: That language change I will use!

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

                            "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                            "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                            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.

                              P Offline
                              P Offline
                              Pete OHanlon
                              wrote on last edited by
                              #20

                              Ah, the use of var. I know that some people use var to do code alignment on variable names; the idea being that it's easier to scan the name if it lines up.

                              private void DoSomething()
                              {
                              var apiEndpoint = new Uri("http://someapi");
                              var retryCount = 10;
                              var longClassName = new ThisIsAReallyLongNameThatWouldReallyScrewUpTheClassNameDeclaration();
                              // body of the method.
                              }

                              Advanced TypeScript Programming Projects

                              N 1 Reply Last reply
                              0
                              • F F ES Sitecore

                                The only benefit is that if you don't understand types then there is a chance your code will work using var even though you don't know why. Also I've found some common style tools dictate you should use var. I don't mind it for

                                var name = "Blah";

                                or

                                var people = new List();

                                but I hate it when people use it for things like

                                var data = SomeFunction();

                                M Offline
                                M Offline
                                megaadam
                                wrote on last edited by
                                #21

                                In C++

                                auto i = small integer // seems rather silly, and obscures signed/unsigned
                                auto v = some complex STL type // is handy
                                auto l = some big elephanting lambda // is required, and why they added it

                                "If we don't change direction, we'll end up where we're going"

                                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!

                                  M Offline
                                  M Offline
                                  Marc Clifton
                                  wrote on last edited by
                                  #22

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

                                    N Offline
                                    N Offline
                                    Nelek
                                    wrote on last edited by
                                    #23

                                    I kind of find it easier to read with var first. But this is more secure, since you have to know what you are going to need and the you create the new instance in the lazy mode. Best of both options, I guess

                                    M.D.V. ;) If something has a solution... Why do we have to worry about?. If it has no solution... For what reason do we have to worry about? Help me to understand what I'm saying, and I'll explain it better to you Rating helpful answers is nice, but saying thanks can be even nicer.

                                    1 Reply Last reply
                                    0
                                    • P Pete OHanlon

                                      Ah, the use of var. I know that some people use var to do code alignment on variable names; the idea being that it's easier to scan the name if it lines up.

                                      private void DoSomething()
                                      {
                                      var apiEndpoint = new Uri("http://someapi");
                                      var retryCount = 10;
                                      var longClassName = new ThisIsAReallyLongNameThatWouldReallyScrewUpTheClassNameDeclaration();
                                      // body of the method.
                                      }

                                      Advanced TypeScript Programming Projects

                                      N Offline
                                      N Offline
                                      Nelek
                                      wrote on last edited by
                                      #24

                                      Pete O'Hanlon wrote:

                                      the idea being that it's easier to scan the name if it lines up.

                                      :thumbsup::thumbsup: That's my main argument (readability) and why I like it. On the other hand, incoming Option #3[^] is good too. It is a bit less readable, but still "forces" you to by type strong but combined with the lazyness / don't break the lines with long names too.

                                      M.D.V. ;) If something has a solution... Why do we have to worry about?. If it has no solution... For what reason do we have to worry about? Help me to understand what I'm saying, and I'll explain it better to you Rating helpful answers is nice, but saying thanks can be even nicer.

                                      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
                                        rnbergren
                                        wrote on last edited by
                                        #25

                                        is it lazy. Sure is. Does it work. Unfortunately yes and Fortunately yes. AS mentioned already when refactoring code and say a variable changes from int to long or even to a string it makes sure the code continues to work. I don't like it. but that does not mean I have never used it. I have and I hate myself for it. But I remember one time I had to write a bit of code. The co-workers insisted that the variable would always be an integer. ALWAYS they said. having some experience I knew probably gonna change. About a year later system requirements changed. I had used var and the code still worked. sooooooo tldr; lazy yes, flexible yes, hate myself yes.

                                        To err is human to really mess up you need a computer

                                        OriginalGriffO 1 Reply Last reply
                                        0
                                        • S Slacker007

                                          it is good for a lot of applications but can be missused very easily. it's main purpose is code readability.

                                          MyMostExcellentBaseClassOfAllClassesInTheWholeWorld myClass = new MyMostExcellentBaseClassOfAllClassesInTheWholeWorld();

                                          or

                                          var myClass = new MyMostExcellentBaseClassOfAllClassesInTheWholeWorld();

                                          It is really good when working with Linq, etc. as well.

                                          F Offline
                                          F Offline
                                          F ES Sitecore
                                          wrote on last edited by
                                          #26

                                          Slacker007 wrote:

                                          it's main purpose is code readability.

                                          Its main purpose is actually anonymous types.

                                          S 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