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 5 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.
  • 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
              • D Daniel Grunwald

                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 Offline
                R Offline
                Rei Miyasaka
                wrote on last edited by
                #54

                Ah. I've hardly had a use for most Marshal calls, exactly for that reason.

                1 Reply Last reply
                0
                • A Anders 0

                  Or even better:

                  var students = new List();

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

                  A Offline
                  A Offline
                  AncientCodeslinger
                  wrote on last edited by
                  #55

                  ~Anders wrote:

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

                  ... and if I have a box of rocks, the label just says rocks.

                  1 Reply Last reply
                  0
                  • P PIEBALDconsult

                    Hmmm... what if object had worked like var to begin with? :suss:

                    A Offline
                    A Offline
                    AncientCodeslinger
                    wrote on last edited by
                    #56

                    PIEBALDconsult wrote:

                    Hmmm... what if object had worked like var to begin with?

                    Then we would need something that worked like object.

                    P 1 Reply Last reply
                    0
                    • A AncientCodeslinger

                      PIEBALDconsult wrote:

                      Hmmm... what if object had worked like var to begin with?

                      Then we would need something that worked like object.

                      P Offline
                      P Offline
                      PIEBALDconsult
                      wrote on last edited by
                      #57

                      Would we?

                      A 1 Reply Last reply
                      0
                      • P PIEBALDconsult

                        Would we?

                        A Offline
                        A Offline
                        AncientCodeslinger
                        wrote on last edited by
                        #58

                        Yes, we would. All sorts of things would break if something declared as object became something else. Something else can be assigned to it, but that's not the same thing. In fact anything can be assigned to it. That's the point.

                        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?).

                          K Offline
                          K Offline
                          Kevin McFarlane
                          wrote on last edited by
                          #59

                          I haven't used C# 3 that much yet but my guess is that something like var just takes a while to get used to. It's probably a bit like when we were all (well,a lot of us) Hungarian notation enthusiasts back in the C/C++/VB days. When first encountering a coding style that shuns it (e.g., .NET) our first thought is "but I can't see at a glance what the types are anymore!" However, nowadays I hate Hungarian and, to be honest, I'd abandoned it about a year before .NET was released. I expect that going forward and with the growing ascendancy of the functional paradigm var will increasingly seem natural.

                          Kevin

                          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

                            K Offline
                            K Offline
                            Kevin McFarlane
                            wrote on last edited by
                            #60

                            Nishant Sivakumar wrote:

                            People seem to have mistaken it to be equivalent to the VB6/COM VARIANT data type

                            Yes this has been ongoing for a year. It's a bit unfortunate that they chose "var" rather than another keyword. People also mistake its meaning for JavaScript's var. However, C# is not alone. Scala also uses var for its type inference. (It uses val for functional immutability.) Nevertheless, despite unfortunate terminology people just need to apply a few moments' thought to these matters before shooting from the hip. Though to be fair there are many critics of var in that thread who fully understand what it means. They just prefer type explicitness to inference.

                            Kevin

                            1 Reply Last reply
                            0
                            • M Mark J Miller

                              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 Offline
                              M Offline
                              MiddleTommy
                              wrote on last edited by
                              #61

                              I personally would not refactor the method name. My method names reflect what the method does not what it returns. It is pure coincidence that many times the object and method coincide. GetCoordinates could return a int[], IEnumerable<int>, List<int>, or a Coordinate object with x,y,and z properties and I would leave the method name alone. I am and always have been a lone developer. I dont have much experience working constantly with teammates code. I do find that relevant //comments make others code much more readable to me than any type declaration. Funny, I feel like I am Microsoft right now advertising the $2500 Total Cost of Ownership of a Win Server is less than a Free Linux OS. I guess everything all depends on who is listening. And where their skills are. (Like you said)

                              modified on Friday, August 21, 2009 9:29 AM

                              M 1 Reply Last reply
                              0
                              • M MiddleTommy

                                I personally would not refactor the method name. My method names reflect what the method does not what it returns. It is pure coincidence that many times the object and method coincide. GetCoordinates could return a int[], IEnumerable<int>, List<int>, or a Coordinate object with x,y,and z properties and I would leave the method name alone. I am and always have been a lone developer. I dont have much experience working constantly with teammates code. I do find that relevant //comments make others code much more readable to me than any type declaration. Funny, I feel like I am Microsoft right now advertising the $2500 Total Cost of Ownership of a Win Server is less than a Free Linux OS. I guess everything all depends on who is listening. And where their skills are. (Like you said)

                                modified on Friday, August 21, 2009 9:29 AM

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

                                MiddleTommy wrote:

                                Funny, I feel like I am Microsoft right now advertising the $2500 Total Cost of Ownership of a Win Server is less than a Free Linux OS.

                                LOL! Thank you for your responses. I enjoy a good discussion. I ended up blogging about var yesterday [^] after we started our discussion and it really seems people (including myself) are pretty set one way or the other. You're certainly right about comments, I try and use them as much as possible when I know others will be reviewing my code. And it really wouldn't make sense to refactor method names - generally a bad idea when it comes to an API.

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