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. Poor var (C#)

Poor var (C#)

Scheduled Pinned Locked Moved The Lounge
csharpc++comdiscussion
62 Posts 36 Posters 1 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.
  • L Lost User

    And shopping. Especially if there is dicounted shoes and chocolate.

    Visit http://www.notreadytogiveup.com/[^] and do something special today.

    G Offline
    G Offline
    grgran
    wrote on last edited by
    #34

    "shoe shopping" ??????? What kind of programmers are you hanging out with ... there is exactly one type of flip-flop ... cheap ... shopping is not really an issue. Chocolate is is only slightly more complicated, it comes in three forms; large, rich and "large and rich". The third is always perferred but not always available. :-)

    1 Reply Last reply
    0
    • A AspDotNetDev

      Yeah, this should have been thought of way long ago. Makes one wonder if any other languages have this feature.

      P Offline
      P Offline
      Pascal Ganaye
      wrote on last edited by
      #35

      Vb has it but they managed to re-use the dim keyword rather that creating a new var keyword. Normal Declarations (without using var):

      C# : int x;
      VB : dim x as integer

      Using var (and Option Infer in VB)

      C# : var x = 5;
      VB : dim x = 5

      Note that VB as also a nice compact dim ... as new ... syntax:

      C# : var x = new Button();
      VB : dim x as new Button()

      Both language look very similar to me now.

      A 1 Reply Last reply
      0
      • M Mycroft Holmes

        I think calling anything "var" is a bad naming convention, that name has way too much baggage.

        P Offline
        P Offline
        Pascal Ganaye
        wrote on last edited by
        #36

        yes dim was better :-)

        1 Reply Last reply
        0
        • N Nish Nishant

          If you look at this week's poll forum, you can see some pretty nasty comments about the C# var keyword. People seem to have mistaken it to be equivalent to the VB6/COM VARIANT data type. A closer equivalent to the VB6/COM VARIANT would be C# 4.0's dynamic keyword. But to attack var based on some wrong assumptions is sad. Remember, all's fair in love and var ;P

          Regards, Nish


          Nish’s thoughts on MFC, C++/CLI and .NET (my blog)
          My latest book : C++/CLI in Action / Amazon.com link

          M Offline
          M Offline
          MiddleTommy
          wrote on last edited by
          #37

          I dont understand var bashing. It is a shortcut use it or dont use it. You can turn intellisense off too. As for readability? I find var makes me digg to understand code more than using traditional static type declarations as a crutch. If var is confusing your understanding of code then your methods are too long and too complex. Also you can always hover over a variable to have visual studio tell you the type of a var declared object.

          M 1 Reply Last reply
          0
          • A AspDotNetDev

            Yeah, this should have been thought of way long ago. Makes one wonder if any other languages have this feature.

            D Offline
            D Offline
            Dave Sexton
            wrote on last edited by
            #38

            JavaScript. Or did you not mean to include dynamic languages?

            But fortunately we have the nanny-state politicians who can step in to protect us poor stupid consumers, most of whom would not know a JVM from a frozen chicken. Bruce Pierson
            Because programming is an art, not a science. Marc Clifton
            I gave up when I couldn't spell "egg". Justine Allen

            A 1 Reply Last reply
            0
            • M Mark J Miller

              I say, use it or don't but it doesn't really save you typing - ever heard of intellisense? Try it, count how many total keystrokes it takes to use var verses typing the whole thing out using intellisense as soon as you get the option. Most of the time you'll type more than 3 characters on the left side to declare the type, but intellisense will then give you the right side for free (1 keystroke to accept the selected type from the intellisense list). You break even - so that little girl w/ the cripped fingers == propaganda :P

              Code responsibly: OWASP.org Mark's blog: developMENTALmadness.blogspot.com Click here for Free Industry White Papers/Magazines! Bill Cosby - "A word to the wise ain't necessary - it's the stupid ones that need the advice."

              D Offline
              D Offline
              Dan Neely
              wrote on last edited by
              #39

              While not defending var itself, intellisense effectiveness depends on the type. For an extreme example start a winform app, begin typing DataGridViewRow, without scrolling you'll have to type all but the last two characters before the type is selected. Immediately before you type the second R it's on 'page 10' of the list. DataGridView itself is almost as bad because of the old DataGrid class.

              The European Way of War: Blow your own continent up. The American Way of War: Go over and help them.

              M 1 Reply Last reply
              0
              • N Nish Nishant

                If you look at this week's poll forum, you can see some pretty nasty comments about the C# var keyword. People seem to have mistaken it to be equivalent to the VB6/COM VARIANT data type. A closer equivalent to the VB6/COM VARIANT would be C# 4.0's dynamic keyword. But to attack var based on some wrong assumptions is sad. Remember, all's fair in love and var ;P

                Regards, Nish


                Nish’s thoughts on MFC, C++/CLI and .NET (my blog)
                My latest book : C++/CLI in Action / Amazon.com link

                J Offline
                J Offline
                Jorgen Sigvardsson
                wrote on last edited by
                #40

                I bet the same people would "hate" compilers if given the question.

                -- Kein Mitleid Für Die Mehrheit

                1 Reply Last reply
                0
                • D Dan Neely

                  While not defending var itself, intellisense effectiveness depends on the type. For an extreme example start a winform app, begin typing DataGridViewRow, without scrolling you'll have to type all but the last two characters before the type is selected. Immediately before you type the second R it's on 'page 10' of the list. DataGridView itself is almost as bad because of the old DataGrid class.

                  The European Way of War: Blow your own continent up. The American Way of War: Go over and help them.

                  M Offline
                  M Offline
                  Mark J Miller
                  wrote on last edited by
                  #41

                  Point well taken. Intellisense doesn't always save a whole lot of typing, but I'm referring to the right side of the declaration. Based on your example:

                  var row = new DataGridViewRow();
                  ^--

                  Here intellisense helps me after 27 characters, then I still need type type "();" taking the total to 30. Intellisense only saved me 2 characters. verses:

                  DataGridViewRow row = new DataGridViewRow();
                  ^-- ^--------------

                  Intellisense kicks in at 13 characters and completes the type and a space for me. Then I type 10 more taking the total to 23. Again, add 3 for "();" and I've typed a total of 26. Using var cost me 4 keystrokes. This is pretty common when comparing intellisense to var because (except when the left side is an interface) the type on the left matches the type on the right and so when you type "new " intellisense will give you the type which is on the left. The only keystroke I need at this point is [TAB]. I can even save an additional keystroke on the left side if I make my intellisense keystroke with [SPACEBAR] instead of [TAB]+[SPACEBAR].

                  Code responsibly: OWASP.org Mark's blog: www.developMENTALmadness.com Bill Cosby - "A word to the wise ain't necessary - it's the stupid ones that need the advice."

                  1 Reply Last reply
                  0
                  • M MiddleTommy

                    I dont understand var bashing. It is a shortcut use it or dont use it. You can turn intellisense off too. As for readability? I find var makes me digg to understand code more than using traditional static type declarations as a crutch. If var is confusing your understanding of code then your methods are too long and too complex. Also you can always hover over a variable to have visual studio tell you the type of a var declared object.

                    M Offline
                    M Offline
                    Mark J Miller
                    wrote on last edited by
                    #42

                    I myself have no problem with var. But it isn't a shortcut (see my post above). In fact, your argument is contradicting. You're saying it forces you to dig in more and requires the additional step of hovering over the variable to understand the type. You're saying it's a shortcut, but what you're describing is additional work. Using var has its place, most especially when working with anonymous types. Another place I use it a lot is unit testing where I am declaring a variable which is an interface and assigning it the value of a mock or stub. But it hasn't ever saved me typing over intellisense except in the latter case. If you choose to use it as a convention because you prefer it, so be it. I won't argue with you and if I work on your project I wouldn't complain either. I don't care that much wither I use it or not. But stop saying it is a shortcut because it isn't unless you code in notepad (I've only ever met one developer who did). As an additional argument against hovering over code snippets, if you are writing an article in code project or posting in the forums you cannot get any help. Also, something I often do because I want to open a code file w/o the overhead of opening an entire project I will open a file in notepad when I don't already have it open - I do this because it saves me time (I have enough RAM to open as many instances of VS as I like). Again, I can't hover over it. So while there is nothing *wrong* with using var, saying it is a shortcut isn't *right*.

                    Code responsibly: OWASP.org Mark's blog: www.developMENTALmadness.com Bill Cosby - "A word to the wise ain't necessary - it's the stupid ones that need the advice."

                    M 1 Reply Last reply
                    0
                    • A Anders 0

                      Or even better:

                      var students = new List();

                      That way, you're not repeating yourself... ;)

                      T Offline
                      T Offline
                      tec goblin
                      wrote on last edited by
                      #43

                      That's my favourite way too. You can see immediately that it's a collection.

                      1 Reply Last reply
                      0
                      • H hairy_hats

                        Possibly because if you want to find a List variable in a long list of declarations, it's much easier to run your eye down a vertical line of types on the left hand side of the = than to have to scan left and right on each line to find the declaration type. var for Linq queries I can see the value of, var for every declaration is confusing.

                        I hope you realise that hamsters are very creative when it comes to revenge. - Elaine

                        T Offline
                        T Offline
                        tec goblin
                        wrote on last edited by
                        #44

                        Apart from the answers below, there is always 1) ctrl+f, 2) the fact that by writing less code you can find the info you need easier, it just sticks out.

                        1 Reply Last reply
                        0
                        • T tec goblin

                          I'll want you to explain me what you would use for a linq query that returns an anonymous type, or what is not enough strongly typed for you in the code var records = new List(); For me, var is a blessing. It saves me of repeating redundant information (why the hell would I want to say in the left AND the right hand side that this is a damned List of Records?).

                          Y Offline
                          Y Offline
                          yassir hannoun
                          wrote on last edited by
                          #45

                          +1 get resharper and you ll get vars everywhere :)

                          1 Reply Last reply
                          0
                          • M Mark J Miller

                            I myself have no problem with var. But it isn't a shortcut (see my post above). In fact, your argument is contradicting. You're saying it forces you to dig in more and requires the additional step of hovering over the variable to understand the type. You're saying it's a shortcut, but what you're describing is additional work. Using var has its place, most especially when working with anonymous types. Another place I use it a lot is unit testing where I am declaring a variable which is an interface and assigning it the value of a mock or stub. But it hasn't ever saved me typing over intellisense except in the latter case. If you choose to use it as a convention because you prefer it, so be it. I won't argue with you and if I work on your project I wouldn't complain either. I don't care that much wither I use it or not. But stop saying it is a shortcut because it isn't unless you code in notepad (I've only ever met one developer who did). As an additional argument against hovering over code snippets, if you are writing an article in code project or posting in the forums you cannot get any help. Also, something I often do because I want to open a code file w/o the overhead of opening an entire project I will open a file in notepad when I don't already have it open - I do this because it saves me time (I have enough RAM to open as many instances of VS as I like). Again, I can't hover over it. So while there is nothing *wrong* with using var, saying it is a shortcut isn't *right*.

                            Code responsibly: OWASP.org Mark's blog: www.developMENTALmadness.com Bill Cosby - "A word to the wise ain't necessary - it's the stupid ones that need the advice."

                            M Offline
                            M Offline
                            MiddleTommy
                            wrote on last edited by
                            #46

                            I agree with you that in some situations it will not save you time. But I am all for uniformity. As a whole if you use var you will code faster. Not only Anonymous types is it a helper. In any Declaration not using the new keyword var comes out on top. Especially if you code like me and refactor a lot. example var coordinate = point.GetCoordinates(); if the return type of GetCoordinates ever changes you dont have to go fix all those declarations. Also often when you compile and a declaration is off further errors are not shown until you fix the declaration and recompile (unless you use Resharper). But to clarify when I said shortcut I was not thinking of keystrokes. Because of the "contradictions" you pointed out let me expound my explanation to un-contradict myself. When you understand the code you are working on Type declaration is not needed. Also The lack of type declaration does not slow you down. When you understand the code you are working on you can code faster because of that understanding. If using var forces you to understand the code better then in the long run you generally code faster. Also as far as I am concerned they should have let us do this coordinate = point.GetCoordinates(); Let the compiler figure out coordinate is a new variable and declare it. But that would have really upset some "C syntax" fan boys. Perhaps officially shortcut is the wrong word. Though I did not mean it the way you suggest I meant it. I could go on and on how var saves me time or shortcut in other words but Let me revoke shortcut and use shorthand instead. var is a shorthand that will save you time(IMHO)

                            M 1 Reply Last reply
                            0
                            • M MiddleTommy

                              I agree with you that in some situations it will not save you time. But I am all for uniformity. As a whole if you use var you will code faster. Not only Anonymous types is it a helper. In any Declaration not using the new keyword var comes out on top. Especially if you code like me and refactor a lot. example var coordinate = point.GetCoordinates(); if the return type of GetCoordinates ever changes you dont have to go fix all those declarations. Also often when you compile and a declaration is off further errors are not shown until you fix the declaration and recompile (unless you use Resharper). But to clarify when I said shortcut I was not thinking of keystrokes. Because of the "contradictions" you pointed out let me expound my explanation to un-contradict myself. When you understand the code you are working on Type declaration is not needed. Also The lack of type declaration does not slow you down. When you understand the code you are working on you can code faster because of that understanding. If using var forces you to understand the code better then in the long run you generally code faster. Also as far as I am concerned they should have let us do this coordinate = point.GetCoordinates(); Let the compiler figure out coordinate is a new variable and declare it. But that would have really upset some "C syntax" fan boys. Perhaps officially shortcut is the wrong word. Though I did not mean it the way you suggest I meant it. I could go on and on how var saves me time or shortcut in other words but Let me revoke shortcut and use shorthand instead. var is a shorthand that will save you time(IMHO)

                              M Offline
                              M Offline
                              Mark J Miller
                              wrote on last edited by
                              #47

                              I like your argument. I can see that refactoring support is a strong plus for var. But if you're refactoring the type do you also refactor the method name? The reason I ask is not to belittle, but rather because the argument I have heard for using var in your scenario is that the method name clearly denotes the type - GetCoordinates returns type Coordinates (or a generic collection of Coordinate types). And so the method name is what maintains readability. I also believe part of this discussion is rooted in context. My experience has been that regardless of the length of time I'm on the project (I've been on a project anywhere from 3 months to 7 years) there's always someone new who comes in or I eventually move to another project. Readability has a high value for me. Plus when I'm working on a team I'd rather have the code read easy so I don't get phone calls on my day off (this doesn't really happen, but rather an extrapolated hypothetical). Regardless of how it sounds, I'm not really against var. I definitely use it in some cases but I prefer not to use it as my main method of declaring local variables outside of using it for anonymous types and unit testing.

                              Code responsibly: OWASP.org Mark's blog: www.developMENTALmadness.com Bill Cosby - "A word to the wise ain't necessary - it's the stupid ones that need the advice."

                              M 1 Reply Last reply
                              0
                              • D Dave Sexton

                                JavaScript. Or did you not mean to include dynamic languages?

                                But fortunately we have the nanny-state politicians who can step in to protect us poor stupid consumers, most of whom would not know a JVM from a frozen chicken. Bruce Pierson
                                Because programming is an art, not a science. Marc Clifton
                                I gave up when I couldn't spell "egg". Justine Allen

                                A Offline
                                A Offline
                                AspDotNetDev
                                wrote on last edited by
                                #48

                                I'm not much of a JavaScript user, but doesn't var in JavaScript act like a variant in VB? That is, a single variable can be assigned values of different types. Var in C# is nice because it enforces one type (i.e., it compile-time checks the type).

                                S 1 Reply Last reply
                                0
                                • P Pascal Ganaye

                                  Vb has it but they managed to re-use the dim keyword rather that creating a new var keyword. Normal Declarations (without using var):

                                  C# : int x;
                                  VB : dim x as integer

                                  Using var (and Option Infer in VB)

                                  C# : var x = 5;
                                  VB : dim x = 5

                                  Note that VB as also a nice compact dim ... as new ... syntax:

                                  C# : var x = new Button();
                                  VB : dim x as new Button()

                                  Both language look very similar to me now.

                                  A Offline
                                  A Offline
                                  AspDotNetDev
                                  wrote on last edited by
                                  #49

                                  Huh, I never thought of that before. I just gained a little more respect for VB (very little ;P ). It's still not quite as efficient as var in C# though. VB:

                                  Dim x As Button = SomeButtonMakingMethod()

                                  C#:

                                  // Never mentions the Button type.
                                  var x = SomeButtonMakingMethod();

                                  Looks like VB can do something like that with option infer, but I'm pretty sure that came out around the same time that C# var did (based on my completely unknowledgable google search just now). So I guess the VB would go something like this (with option infer turned on):

                                  ' Never mentions the Button type.
                                  Dim x = SomeButtonMakingMethod()

                                  1 Reply Last reply
                                  0
                                  • D Daniel Grunwald

                                    unsafe was named so 'scary' and buried under an extra compiler option that nearly no one is using it. I've seen code doing manual marshaling (Marshal.AllocHGlobal, Marshal.Copy, etc.) for P/Invoke calls which could have been replaced with a simple fixed block around the P/Invoke call.

                                    R Offline
                                    R Offline
                                    Rei Miyasaka
                                    wrote on last edited by
                                    #50

                                    I don't think any of the Marshal calls let you point at arbitrary memory addresses, does it? It probably is a tad safer than unsafe. Correct me if I'm wrong.

                                    D 1 Reply Last reply
                                    0
                                    • A Anders 0

                                      Or even better:

                                      var students = new List();

                                      That way, you're not repeating yourself... ;)

                                      B Offline
                                      B Offline
                                      Brady Kelly
                                      wrote on last edited by
                                      #51

                                      That's what I do, but I was trying to establish some sort of raport with a variably challenged paradigm. :laugh:

                                      1 Reply Last reply
                                      0
                                      • R Rei Miyasaka

                                        I don't think any of the Marshal calls let you point at arbitrary memory addresses, does it? It probably is a tad safer than unsafe. Correct me if I'm wrong.

                                        D Offline
                                        D Offline
                                        Daniel Grunwald
                                        wrote on last edited by
                                        #52

                                        This will copy one byte to a random memory address:

                                        int rnd = new Random().Next();
                                        Marshal.Copy(new byte[] { 42 }, 0, (IntPtr)rnd, 1);

                                        How is this safer than

                                        unsafe {
                                        *((byte*)rnd) = 42;
                                        }

                                        ? At least with unsafe code, you see the "unsafe" warning right in the code.

                                        R 1 Reply Last reply
                                        0
                                        • A AspDotNetDev

                                          I'm not much of a JavaScript user, but doesn't var in JavaScript act like a variant in VB? That is, a single variable can be assigned values of different types. Var in C# is nice because it enforces one type (i.e., it compile-time checks the type).

                                          S Offline
                                          S Offline
                                          Shog9 0
                                          wrote on last edited by
                                          #53

                                          aspdotnetdev wrote:

                                          doesn't var in JavaScript act like a variant in VB?

                                          Pretty much. The only notable difference is that it works that way consistently - there's no appreciable difference between a variable holding a value and one holding a reference to an object. C#'s var is just a handy shorthand notation for a normal typed variable... I can't help but think it would be much more useful if C# had something like C++-style templates... And sure enough, the next version of C++ introduces its own version of var with the auto keyword! :-)

                                          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