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. :^)

    F Offline
    F Offline
    Fabio Franco
    wrote on last edited by
    #23

    I think its a really bad idea too. It opens the doors to all kind of bad/lazy code. Poor testers, reafactores, inheritors... It's even worse with the introduction of dynamic keyword, which flushes type safety down the toiled. I see .net going downhill. :~

    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

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

      Marc Clifton wrote:

      I still don't see the purpose of var except for Linq and/or lambda expressions.

      Then don't use it. -Max

      M 1 Reply Last reply
      0
      • L Lost User

        Marc Clifton wrote:

        I still don't see the purpose of var except for Linq and/or lambda expressions.

        Then don't use it. -Max

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

        Max Peck wrote:

        Then don't use it.

        I don't. :) But somewhere in this morass of opinions, there ought to be some actual way of determining best practices, and that's what I keep trying to figure out. Marc

        L 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

          E Offline
          E Offline
          Ed K
          wrote on last edited by
          #26

          Because there are still those using Re-factor who right click and change all to 'var' as a first step to obfuscating their code.

          ed ~"Watch your thoughts; they become your words. Watch your words they become your actions. Watch your actions; they become your habits. Watch your habits; they become your character. Watch your character; it becomes your destiny." -Frank Outlaw.

          T 1 Reply Last reply
          0
          • M Marc Clifton

            Max Peck wrote:

            Then don't use it.

            I don't. :) But somewhere in this morass of opinions, there ought to be some actual way of determining best practices, and that's what I keep trying to figure out. Marc

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

            Marc, Best practices? From this group? Are you nuts? :laugh: You'll definitely get some good input from the guys here but "best practices" is something I've never even see an organized company maintain without great difficulty let alone a forum of rogue programmers like us! Don't tell me you don't still use GOTO. ;-) -Max

            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. :^)

              M Offline
              M Offline
              martinluch
              wrote on last edited by
              #28

              Some times you dont want to create a class to expose only a couple of properties. What do you think about this code...

              // Build an anonymous type
              var anon1 = new { number = 4, square = 4 * 4 };
              // Do something with it
              Console.WriteLine(string.Format("Square of {0} is {1}", anon1.number, anon1.square));

              or...

              List<object> myList = new List<object>(); // Build a new collection
              for (int i = 0; i < 5; i++)
              {
              var anon = new { number = i , square = i * i }; // Build an anonymous type
              myList.Add(anon); // Start adding anonymous types to it
              }

              foreach (var anonymousType in myList)
              {
              PropertyInfo[] MyProperties = anonymousType.GetType().GetProperties(); // Reflect the type

                  foreach (var Property in MyProperties) 
                  {
                  	Console.WriteLine(Property.GetValue(anonymousType, null).ToString()); // Do what you want with the property
                  }
              

              }

              Useful or not? Up to you...

              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

                J Offline
                J Offline
                John Oxley
                wrote on last edited by
                #29

                But you still have to type in the type the first time round. Plus the line is longer and more cumbersome to read.

                M 1 Reply Last reply
                0
                • J John Oxley

                  But you still have to type in the type the first time round. Plus the line is longer and more cumbersome to read.

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

                  John Oxley wrote:

                  Plus the line is longer and more cumbersome to read.

                  I must read code differently from other people. I've never noticed that the "old" style is cumbersome! Marc

                  1 Reply Last reply
                  0
                  • D dazfuller

                    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 Offline
                    J Offline
                    John Oxley
                    wrote on last edited by
                    #31

                    var does compile time inference of the type. It looks at the right hand side of the equals and says, ah that's a string therefore that's what I shall be. Not an int. Not a double. Not even shall I pretend to be a DateTime. The day that someone tries to made me a TcpClient, I shall have my trusty compiler beat thee with a stick.

                    var transaction = repository.GetTransaction(id);

                    I'm guessing that transaction is going to be of the type AKittyLitter. Yes that makes sense. Oh and id is the name of my CEO's pet gerbil. (If you use Notepad / vim / anything else stupid, I'm not talking to you) You're working in Visual Studio, not nano. Use it.

                    var x = y.Foo();

                    The bloke who actually has that in his release project should be shot. I agree with a previous poster that your variable names and method names should mean something. If repository.GetTransaction doesn't return a Transaction object, then I've designed my code stupidly. If Transaction doesn't have a decimal Amount property on it, well, then Visual Studio will tell you before the 3rd letter. Go read this: http://omergertel.com/2010/07/04/how-to-read-code/[^]

                    D 1 Reply Last reply
                    0
                    • J John Oxley

                      var does compile time inference of the type. It looks at the right hand side of the equals and says, ah that's a string therefore that's what I shall be. Not an int. Not a double. Not even shall I pretend to be a DateTime. The day that someone tries to made me a TcpClient, I shall have my trusty compiler beat thee with a stick.

                      var transaction = repository.GetTransaction(id);

                      I'm guessing that transaction is going to be of the type AKittyLitter. Yes that makes sense. Oh and id is the name of my CEO's pet gerbil. (If you use Notepad / vim / anything else stupid, I'm not talking to you) You're working in Visual Studio, not nano. Use it.

                      var x = y.Foo();

                      The bloke who actually has that in his release project should be shot. I agree with a previous poster that your variable names and method names should mean something. If repository.GetTransaction doesn't return a Transaction object, then I've designed my code stupidly. If Transaction doesn't have a decimal Amount property on it, well, then Visual Studio will tell you before the 3rd letter. Go read this: http://omergertel.com/2010/07/04/how-to-read-code/[^]

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

                      What's more useful though is if a maintainer can do read-the-code time inference of the type. If y.Foo() returned a NappySack object then they can go have a look at that type and figure out what it can do. With a var they'd have to go and look at the y.Foo() to figure out what is returned and then figure it out from there. And I don't want my compiler having to figure this out, it takes it long enough as it is already to do anything useful and I can only spend so much of my day making cups of coffee!

                      1 Reply Last reply
                      0
                      • H Henk Nicolai

                        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 Offline
                        A Offline
                        AspDotNetDev
                        wrote on last edited by
                        #33

                        Pft, why even specify a type? Check out what this person has to say.

                        [Forum Guidelines]

                        1 Reply Last reply
                        0
                        • E Ed K

                          Because there are still those using Re-factor who right click and change all to 'var' as a first step to obfuscating their code.

                          ed ~"Watch your thoughts; they become your words. Watch your words they become your actions. Watch your actions; they become your habits. Watch your habits; they become your character. Watch your character; it becomes your destiny." -Frank Outlaw.

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

                          Ed K wrote:

                          Because there are still those using Re-factor who right click and change all to 'var' as a first step to obfuscating their code.

                          I guess that's their problem then isn't it :)

                          Todd Smith

                          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