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. I still think the "var" in C# is a really bad idea

I still think the "var" in C# is a really bad idea

Scheduled Pinned Locked Moved The Lounge
csharp
34 Posts 23 Posters 38 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.
  • J jpg 0

    Consider this code:

    var num = MyMath.Add( 123, 789 );

    By just reading the code, you won't be able to know whether num is an int32, int16, float, double, or any other types. :^)

    S Offline
    S Offline
    Simon P Stevens
    wrote on last edited by
    #3

    Agreed, that is bad code. But on the other hand consider this:

    var myDictionary = new Dictionary<Guid, SomeClass>(sourceData);

    which is more readable than this:

    Dictionary<Guid, SomeClass> myDictionary = new Dictionary<Guid, SomeClass>(sourceData);

    As with everything, it's use should be considered and appropriate. I use var only where the type is obvious from the right hand side of the statement (and for those anonymous linq types).

    Simon

    E M 2 Replies Last reply
    0
    • J jpg 0

      Consider this code:

      var num = MyMath.Add( 123, 789 );

      By just reading the code, you won't be able to know whether num is an int32, int16, float, double, or any other types. :^)

      C Offline
      C Offline
      CPallini
      wrote on last edited by
      #4

      Well, I actually would keep the "var" and drop the "C#"... :rolleyes:

      If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
      This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
      [My articles]

      modified on Friday, July 2, 2010 11:52 AM

      L 1 Reply Last reply
      0
      • S Simon P Stevens

        Agreed, that is bad code. But on the other hand consider this:

        var myDictionary = new Dictionary<Guid, SomeClass>(sourceData);

        which is more readable than this:

        Dictionary<Guid, SomeClass> myDictionary = new Dictionary<Guid, SomeClass>(sourceData);

        As with everything, it's use should be considered and appropriate. I use var only where the type is obvious from the right hand side of the statement (and for those anonymous linq types).

        Simon

        E Offline
        E Offline
        Electron Shepherd
        wrote on last edited by
        #5

        At least in C# they didn't take an existing keyword and change the meaning...

        Server and Network Monitoring

        1 Reply Last reply
        0
        • J jpg 0

          Consider this code:

          var num = MyMath.Add( 123, 789 );

          By just reading the code, you won't be able to know whether num is an int32, int16, float, double, or any other types. :^)

          J Offline
          J Offline
          J4amieC
          wrote on last edited by
          #6

          .jpg wrote:

          By just reading the code, you won't be able to know whether num is an int32, int16, float, double, or any other types.

          But the compiler will, and at the end of the day, that's what is important.

          L 1 Reply Last reply
          0
          • J jpg 0

            Consider this code:

            var num = MyMath.Add( 123, 789 );

            By just reading the code, you won't be able to know whether num is an int32, int16, float, double, or any other types. :^)

            T Offline
            T Offline
            Todd Smith
            wrote on last edited by
            #7

            .jpg wrote:

            Consider this code: var num = MyMath.Add( 123, 789 ); By just reading the code, you won't be able to know whether num is an int32, int16, float, double, or any other types.

            If type matters then don't use var. How hard can that be?

            Todd Smith

            S E 2 Replies Last reply
            0
            • J jpg 0

              Consider this code:

              var num = MyMath.Add( 123, 789 );

              By just reading the code, you won't be able to know whether num is an int32, int16, float, double, or any other types. :^)

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

              Well how about this:

              static void Main(string[] args)
              {
              SomeFunction(SomeClass.SomeOtherFunction(arg[0]));
              }

              static void SomeFunction(int i)
              {
              throw new Exception();
              }

              static void SomeFunction(double d)
              {
              Console.WriteLine(d);
              }

              Don't look at the terrible coding style too much. This is just plain C#1 right? But do you know, without looking up SomeClass.SomeOtherFunction, what will happen? I sure don't.

              S 1 Reply Last reply
              0
              • S Simon P Stevens

                Agreed, that is bad code. But on the other hand consider this:

                var myDictionary = new Dictionary<Guid, SomeClass>(sourceData);

                which is more readable than this:

                Dictionary<Guid, SomeClass> myDictionary = new Dictionary<Guid, SomeClass>(sourceData);

                As with everything, it's use should be considered and appropriate. I use var only where the type is obvious from the right hand side of the statement (and for those anonymous linq types).

                Simon

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

                Except that in the second example, after hitting spacebar after the "new", the editor fills in the rest, so either way, you have to type in the type. Uh. No pun intended. I still don't see the purpose of var except for Linq and/or lambda expressions. Marc

                P M F L J 5 Replies Last reply
                0
                • M Marc Clifton

                  Except that in the second example, after hitting spacebar after the "new", the editor fills in the rest, so either way, you have to type in the type. Uh. No pun intended. I still don't see the purpose of var except for Linq and/or lambda expressions. Marc

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

                  Marc Clifton wrote:

                  xcept that in the second example, after hitting spacebar after the "new", the editor fills in the rest, so either way, you have to type in the type. Uh. No pun intended.

                  Notepad has never done this for me. ;P

                  "WPF has many lovers. It's a veritable porn star!" - Josh Smith

                  As Braveheart once said, "You can take our freedom but you'll never take our Hobnobs!" - Martin Hughes.

                  My blog | My articles | MoXAML PowerToys | Onyx

                  1 Reply Last reply
                  0
                  • M Marc Clifton

                    Except that in the second example, after hitting spacebar after the "new", the editor fills in the rest, so either way, you have to type in the type. Uh. No pun intended. I still don't see the purpose of var except for Linq and/or lambda expressions. Marc

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

                    Marc Clifton wrote:

                    var except for Linq and/or lambda expressions

                    Oh, so you can use it for other things as well :-O it never even occurred to me.

                    Never underestimate the power of human stupidity RAH

                    1 Reply Last reply
                    0
                    • J jpg 0

                      Consider this code:

                      var num = MyMath.Add( 123, 789 );

                      By just reading the code, you won't be able to know whether num is an int32, int16, float, double, or any other types. :^)

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

                      .jpg wrote:

                      you won't be able to know whether num is an int32, int16, float, double, or any other types

                      Much of the time, knowing the exact type doesn't matter (in the example you gave, you know it's probably a number). And you could find out by mousing over "Add", or by typing "num" (the tooltip will tell you the type). Of course, typing "int" isn't going to cause you much more trouble than typing "var", so it's probably more appropriate here to just type "int". Still, I wouldn't say what you have shown demonstrates why var in C# is "a really bad idea". In fact, it seems like a pretty good idea in many situations (covered by other posters above already).

                      [Forum Guidelines]

                      1 Reply Last reply
                      0
                      • J J4amieC

                        .jpg wrote:

                        By just reading the code, you won't be able to know whether num is an int32, int16, float, double, or any other types.

                        But the compiler will, and at the end of the day, that's what is important.

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

                        J4amieC wrote:

                        But the compiler will, and at the end of the day, that's what is important.

                        Is it? I think not, sir! What is most important in the long run is that the code is maintainable, as the costs of maintenance outweigh the costs of development (usually). That said, var is useful when used appropriately.

                        ___________________________________________ .\\axxx (That's an 'M')

                        1 Reply Last reply
                        0
                        • T Todd Smith

                          .jpg wrote:

                          Consider this code: var num = MyMath.Add( 123, 789 ); By just reading the code, you won't be able to know whether num is an int32, int16, float, double, or any other types.

                          If type matters then don't use var. How hard can that be?

                          Todd Smith

                          S Offline
                          S Offline
                          Super Lloyd
                          wrote on last edited by
                          #14

                          exactly my thought!

                          A train station is where the train stops. A bus station is where the bus stops. On my desk, I have a work station.... _________________________________________________________ My programs never have bugs, they just develop random features.

                          1 Reply Last reply
                          0
                          • L Lost User

                            Well how about this:

                            static void Main(string[] args)
                            {
                            SomeFunction(SomeClass.SomeOtherFunction(arg[0]));
                            }

                            static void SomeFunction(int i)
                            {
                            throw new Exception();
                            }

                            static void SomeFunction(double d)
                            {
                            Console.WriteLine(d);
                            }

                            Don't look at the terrible coding style too much. This is just plain C#1 right? But do you know, without looking up SomeClass.SomeOtherFunction, what will happen? I sure don't.

                            S Offline
                            S Offline
                            Super Lloyd
                            wrote on last edited by
                            #15

                            Good one! :laugh:

                            A train station is where the train stops. A bus station is where the bus stops. On my desk, I have a work station.... _________________________________________________________ My programs never have bugs, they just develop random features.

                            1 Reply Last reply
                            0
                            • J jpg 0

                              Consider this code:

                              var num = MyMath.Add( 123, 789 );

                              By just reading the code, you won't be able to know whether num is an int32, int16, float, double, or any other types. :^)

                              D Offline
                              D Offline
                              dazfuller
                              wrote on last edited by
                              #16

                              Agreed, in a typed language what's the point of not defining the type? If you don't want to define the type then use Python

                              J 1 Reply Last reply
                              0
                              • J jpg 0

                                Consider this code:

                                var num = MyMath.Add( 123, 789 );

                                By just reading the code, you won't be able to know whether num is an int32, int16, float, double, or any other types. :^)

                                S Offline
                                S Offline
                                Stuart Dootson
                                wrote on last edited by
                                #17

                                The specification of MyMath.Add is part of the code, right? So read that bit... And whatever you do, don't use a language like Haskell or Ocaml, which does real, powerful type deduction - it'll blow your mind...

                                Java, Basic, who cares - it's all a bunch of tree-hugging hippy cr*p CodeProject MVP for 2010 - who'd'a thunk it!

                                1 Reply Last reply
                                0
                                • J jpg 0

                                  Consider this code:

                                  var num = MyMath.Add( 123, 789 );

                                  By just reading the code, you won't be able to know whether num is an int32, int16, float, double, or any other types. :^)

                                  A Offline
                                  A Offline
                                  Adriaan Davel
                                  wrote on last edited by
                                  #18

                                  I like var because it takes focus off the type, and places it on the variable name. With a good variable name var actually improves your code if you were to change the type later. Consider: int customerBalance = GetCustomerBalance();, which has to be changed to decimal customerBalance = GetCustomerBalance(); after the function return is changed, where var customerBalance = GetCustomerBalance(); would have worked both ways. If you have enough dicipline in variable names one wouldn't need to look at the types (mostly), and var promotes this (to a degree).

                                  ____________________________________________________________ Be brave little warrior, be VERY brave

                                  1 Reply Last reply
                                  0
                                  • J jpg 0

                                    Consider this code:

                                    var num = MyMath.Add( 123, 789 );

                                    By just reading the code, you won't be able to know whether num is an int32, int16, float, double, or any other types. :^)

                                    H Offline
                                    H Offline
                                    Henk Nicolai
                                    wrote on last edited by
                                    #19

                                    Agreed... So why don't we have some kind of Visual Studio option that does all the type-inference and replaces all those 'var's with actual inferred types? I thought the main purpose of 'var' was to increase productivity... Or, maybe the following syntax should be allowed: Dictionary<string> myDictionary = new(StringComparer.OrdinalIgnoreCase); (E.g. no extra type declaration if selecting a constructor from the same class. Not very readable though if you're not used to it.) - DerHenker

                                    A 1 Reply Last reply
                                    0
                                    • J jpg 0

                                      Consider this code:

                                      var num = MyMath.Add( 123, 789 );

                                      By just reading the code, you won't be able to know whether num is an int32, int16, float, double, or any other types. :^)

                                      A Offline
                                      A Offline
                                      Alexander DiMauro
                                      wrote on last edited by
                                      #20

                                      .jpg wrote:

                                      var num = MyMath.Add( 123, 789 );

                                      Once again, your example is a perfect example of PEBKAC, and not an example of a problem with var. If used as intended, 'var' is extremely useful. Your example is NOT an intended use. While it can be done, you are absolutely correct. You don't know what the return value will be. But, when used with LINQ, it is EXTREMELY useful, and that was really its intended purpose. It can also help in situations like this: SomeInsanelyLongNameThatNeverEnds<LongLongName, SuperLongNameAgain> someVar = new...you get the picture. Throw a var in there and it shortens it considerably without losing any information. That is really, IMHO, the only time to use var outside of LINQ, when you don't lose any information. The final point is...get ReSharper. If you are unsure of return values, but want to display them, type in 'var', and then select 'specify type explicitly' in ReSharper, and it puts the return type in there for you. VERY useful! I use that one all the time.

                                      1 Reply Last reply
                                      0
                                      • M Marc Clifton

                                        Except that in the second example, after hitting spacebar after the "new", the editor fills in the rest, so either way, you have to type in the type. Uh. No pun intended. I still don't see the purpose of var except for Linq and/or lambda expressions. Marc

                                        F Offline
                                        F Offline
                                        Filip Duyck
                                        wrote on last edited by
                                        #21

                                        Code is written once and read many times. Why force the reader to read the same information twice? On top of that, using 'var' somewhat forces people to pick more meaningful names, and it makes refactoring easier. Of course, that is only my opinion. You're entitled to yours, and I'm sure many people would agree with you.

                                        1 Reply Last reply
                                        0
                                        • C CPallini

                                          Well, I actually would keep the "var" and drop the "C#"... :rolleyes:

                                          If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
                                          This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
                                          [My articles]

                                          modified on Friday, July 2, 2010 11:52 AM

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

                                          Let's name it DIM!

                                          I are Troll :suss:

                                          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