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. An interesting (or not) thing about C#'s var

An interesting (or not) thing about C#'s var

Scheduled Pinned Locked Moved The Lounge
csharppythonvisual-studiocomfunctional
43 Posts 12 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

    [disclaimer] OK, this is probably a totally lame post. [/disclaimer] When you use var (or even if you just embed the rvalue as a parameter to another method), you don't need to reference the assembly containing the type. var prop = rec.GetType().GetProperty(propName); Doesn't require using System.Reflection; And Intellisense works just fine. But this: PropertyInfo prop = rec.GetType().GetProperty(propName); Does. Neither does this: object val = Converter.Convert(data, rec.GetType().GetProperty(propName).PropertyType); I find that, well, interesting. (I'm using VS2015, lest anyone even care.) Marc

    Imperative to Functional Programming Succinctly Contributors Wanted for Higher Order Programming Project! Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny

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

    var seem way too close to the VB6 variant type so I have trouble typing it. The same applies for GOTO, just can't bring myself to use them.

    Never underestimate the power of human stupidity RAH

    Richard DeemingR 1 Reply Last reply
    0
    • M Marc Clifton

      [disclaimer] OK, this is probably a totally lame post. [/disclaimer] When you use var (or even if you just embed the rvalue as a parameter to another method), you don't need to reference the assembly containing the type. var prop = rec.GetType().GetProperty(propName); Doesn't require using System.Reflection; And Intellisense works just fine. But this: PropertyInfo prop = rec.GetType().GetProperty(propName); Does. Neither does this: object val = Converter.Convert(data, rec.GetType().GetProperty(propName).PropertyType); I find that, well, interesting. (I'm using VS2015, lest anyone even care.) Marc

      Imperative to Functional Programming Succinctly Contributors Wanted for Higher Order Programming Project! Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny

      realJSOPR Offline
      realJSOPR Offline
      realJSOP
      wrote on last edited by
      #27

      I don't like var. If it's so goddamn wonderful, why require its use at all? Why bother even defining types at all? If I wanted to code like that, I'd use VB.

      ".45 ACP - because shooting twice is just silly" - JSOP, 2010
      -----
      You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
      -----
      When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

      Richard DeemingR L M J 4 Replies Last reply
      0
      • L Lost User

        Eddy Vluggen wrote:

        The cast is there to specifically say which interface is expected.

        Yes, but why? Why do you need that? It is not necessary and was my point. By placing the cast you create a potential run time error that was not even necessary.

        Eddy Vluggen wrote:

        That argument is pro weak typing, isn't it?

        Yes. There is no need for strict typing in MANY cases (no not all). And a good programmer should know how to use that to their advantage....

        Eddy Vluggen wrote:

        The DbProvider returns a class, but I only use the interface - so when I can be specific about which type I expect, I do.

        OK. Do you know what an adapter is? (rhetorical question actually)

        Eddy Vluggen wrote:

        I merely state that not being an idiot would mean that you verify, and not generalize.

        Not sure what you are saying, but yeah you should have verification. Most of the people that posted issues with var seemed to blame it for 2 things 1. The escaped failure 2. The fact the failure escaped Neither are true and simple verification procedures and tests would have been far more appropriate. Is this a generalization. Yep, but that is what I am seeing in all of the respondents and near all conversations I have had with people that dislike var.

        Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet. The interesting thing about software is it can not reproduce, until it can.

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

        N_tro_P wrote:

        By placing the cast you create a potential run time error that was not even necessary

        At run-time? :)

        N_tro_P wrote:

        (rhetorical question actually)

        Yeah, that helps clarifying the topic :thumbsup:

        Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^][](X-Clacks-Overhead: GNU Terry Pratchett)

        L 1 Reply Last reply
        0
        • T TheGreatAndPowerfulOz

          I'm with you on var, I use it myself when the type is obvious. But this statement

          N_tro_P wrote:

          It just amplifies his bad practice.

          Is the only really cogent argument against using var.

          #SupportHeForShe Government can give you nothing but what it takes from somebody else. A government big enough to give you everything you want is big enough to take everything you've got, including your freedom.-Ezra Taft Benson You must accept 1 of 2 basic premises: Either we are alone in the universe or we are not alone. Either way, the implications are staggering!-Wernher von Braun

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

          TheGreatAndPowerfulOz

          I'm with you

          Was that a pig that just flew by my window? ;P

          TheGreatAndPowerfulOz

          N_tro_P wrote:

          It just amplifies his bad practice.

          Is the only really cogent argument against using var.

          But in all seriousness, that is also what I notice. That's not to say there are not places it shouldn't be used, but all of the naysayers seem to completely over generalize and just consider it "bad", and it seems this is why.

          Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet. The interesting thing about software is it can not reproduce, until it can.

          1 Reply Last reply
          0
          • Sander RosselS Sander Rossel

            N_tro_P wrote:

            I have found var is a religious argument

            Sounds pretty religious to you. I've pointed out some scenarios where NOT using var may help in catching errors early and all you did is call me a failure and a bad programmer who doesn't know what he's doing and compare free MSDN server space to actual production environments. I actually checked if you were our regular troll, but you have a little too much rep for that. Seems you're just bad mannered. I'm quite done discussing this with you. I do use var though. Probably a lot more often than you don't :)

            Read my (free) ebook Object-Oriented Programming in C# Succinctly. Visit my blog at Sander's bits - Writing the code you need. Or read my articles here on CodeProject.

            Simplicity is prerequisite for reliability. — Edsger W. Dijkstra

            Regards, Sander

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

            Sander Rossel wrote:

            I've pointed out some scenarios where NOT using var may help in catching errors early

            No you pointed out scenarios where your lack of testing was re-emphasized by not using var and then getting a different error than was even your actual problem. I would prefer having clear testing that gives clear errors of went wrong, and not use a weak type cast as a scape goat for the actual error and the lack of system testing.

            Sander Rossel wrote:

            all you did is call me a failure and a bad programmer

            No, actually I said var has a bad rep because when a bad programmer uses it the good programmers were cringing anyways, and now cringe at var. Sort of like Pavlov's dog and the bell. There was never anything wrong with var, but you have falsely associated the two.

            Sander Rossel wrote:

            doesn't know what he's doing and compare free MSDN server space to actual production environments.

            My profile is pretty open. You can claim I don't know what I am doing, but the chances are I have quite a bit more experience than you. Your attempted insult I shrug off with, "LMAO!"

            Sander Rossel wrote:

            I'm quite done discussing this with you.

            You were never discussing. Your post above is proof. I gave you a chance to justify your environment rather than scapegoating it, and you attempted to use that opportunity at a childish insult. If I have learned one thing as a seasoned architect, it is there is always more to learn. I admit I could be wrong but as of yet not one of you nay sayers have actually made a solid argument other than 1. I don't like it 2. We have a team of nimkapoops that use it so I assume it is bad 3. We don't test so we incorrectly think we are protected from errors by using strong types Come up with an actual argument and THEN you have a discussion. Else, you just look like the guy mentioned in 2.

            Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet. The interesting thing about software is it can not reproduce, until it can.

            1 Reply Last reply
            0
            • L Lost User

              N_tro_P wrote:

              By placing the cast you create a potential run time error that was not even necessary

              At run-time? :)

              N_tro_P wrote:

              (rhetorical question actually)

              Yeah, that helps clarifying the topic :thumbsup:

              Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^][](X-Clacks-Overhead: GNU Terry Pratchett)

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

              Eddy Vluggen wrote:

              At run-time? :)

              Yes. Are you seriously having issues over a hyphen in a poorly discussed topic in the lounge? No wonder you have issues with var.

              Eddy Vluggen wrote:

              Yeah, that helps clarifying the topic :thumbsup:

              I thought so.

              Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet. The interesting thing about software is it can not reproduce, until it can.

              L 1 Reply Last reply
              0
              • M Mladen Jankovic

                Marc Clifton wrote:

                you don't need to reference the assembly containing the type

                Wait a second, you mean it does not require referencing assembly or using directive for the namespace?

                GeoGame for Windows Phone | The Lounge Explained In 5 Minutes

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

                Mladen Janković wrote:

                Wait a second, you mean it does not require referencing assembly or using directive for the namespace?

                That is correct. This makes it very useful when building adapters connecting to DB layer and even in the usage of the adapters.

                Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet. The interesting thing about software is it can not reproduce, until it can.

                1 Reply Last reply
                0
                • M Mycroft Holmes

                  var seem way too close to the VB6 variant type so I have trouble typing it. The same applies for GOTO, just can't bring myself to use them.

                  Never underestimate the power of human stupidity RAH

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

                  Mycroft Holmes wrote:

                  var seem way too close to the VB6 variant type

                  A common misconception. var doesn't mean that your variable is untyped, or typed as object. It just means that the compiler decides what type the variable should be based on the value assigned to it when it is declared.

                  var s = "Hello"; // Compiles to exactly the same IL as "string s = ..."
                  s = 42; // Compiler error - cannot assign an Int32 to a String

                  Totally unlike the Variant type, where the variable could contain anything, and all calls were late-bound:

                  Dim s As Variant
                  s = "Hello" ' Oh, it's a string...
                  s = 42 ' Now it's a Long - that's fine...
                  Set s = New ADODB.Connection ' An object? No problem...


                  "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
                  • realJSOPR realJSOP

                    I don't like var. If it's so goddamn wonderful, why require its use at all? Why bother even defining types at all? If I wanted to code like that, I'd use VB.

                    ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                    -----
                    You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                    -----
                    When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

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

                    John Simmons / outlaw programmer wrote:

                    Why bother even defining types at all?

                    Because var doesn't mean "untyped". It means, "the type of this variable is obvious to the compiler, so I don't need to bother writing it".


                    "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

                    J 1 Reply Last reply
                    0
                    • L Lost User

                      Eddy Vluggen wrote:

                      At run-time? :)

                      Yes. Are you seriously having issues over a hyphen in a poorly discussed topic in the lounge? No wonder you have issues with var.

                      Eddy Vluggen wrote:

                      Yeah, that helps clarifying the topic :thumbsup:

                      I thought so.

                      Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet. The interesting thing about software is it can not reproduce, until it can.

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

                      N_tro_P wrote:

                      Are you seriously having issues over a hyphen

                      No. Just the difference with compile-time :)

                      Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^][](X-Clacks-Overhead: GNU Terry Pratchett)

                      L 2 Replies Last reply
                      0
                      • realJSOPR realJSOP

                        I don't like var. If it's so goddamn wonderful, why require its use at all? Why bother even defining types at all? If I wanted to code like that, I'd use VB.

                        ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                        -----
                        You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                        -----
                        When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

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

                        John Simmons / outlaw programmer wrote:

                        If it's so goddamn wonderful, why require its use at all?

                        It's not required. The post was showing a nice benefit. If you don't like benefits... Well, that's your problem I guess.

                        John Simmons / outlaw programmer wrote:

                        Why bother even defining types at all?

                        Why bother using high level languages? Why not just code in 1s and 0s? Yeah, silly question in response to a silly question. The fact is strong types are needed, but in my experience quite rarely. Weak types allow for improved architectural principles like development views and extensibility. The argument often made is the is errors that occur, but it is in fact a red herring in that the systems testability (another architectural principle) is lacking. That's not to say it has to be, but due to budget or lack of developer concern for tests or some other poorly justified reason it has been omitted from the system. The logic then becomes circular. We don't like it cause we found an error one time when someone used it. The truth is the error existed not because of var, and the nay sayers will usually acknowledge this. Where the gap is then, is on how it would have been caught or observed otherwise. Which goes back to testing. The testing should have been in place regardless, because it actually catches errors. Saying we use strong types because it catches errors is not observing the real issue. For one, strong types won't catch all of the errors. For two, proper testing would catch the same errors even if weak typed. Therefore, it is a red herring.

                        Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet. The interesting thing about software is it can not reproduce, until it can.

                        1 Reply Last reply
                        0
                        • L Lost User

                          N_tro_P wrote:

                          Are you seriously having issues over a hyphen

                          No. Just the difference with compile-time :)

                          Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^][](X-Clacks-Overhead: GNU Terry Pratchett)

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

                          Your example would not have a "compile-time" error. It would result in a "run-time" error if it was a bad cast.

                          Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet. The interesting thing about software is it can not reproduce, until it can.

                          1 Reply Last reply
                          0
                          • L Lost User

                            N_tro_P wrote:

                            Are you seriously having issues over a hyphen

                            No. Just the difference with compile-time :)

                            Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^][](X-Clacks-Overhead: GNU Terry Pratchett)

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

                            Eddy Vluggen wrote:

                            No. Just the difference with compile-time :)

                            Your example would not result in a "compile-time" error but in fact a "run-time" error. Proof:

                            public interface IThingy
                            {

                            }
                            
                            public class Parent : IThingy
                            {
                            
                            }
                            
                            public class Child : Parent
                            {
                            
                            }
                            
                            public class Monkey
                            {
                            
                            }
                            
                            public class User
                            {
                                public void Test()
                                {
                                    var monkey = new Monkey();
                                    var child = (IThingy)monkey;
                            
                                }
                            }
                            

                            This code compiles and will result in a bad casting exception. You are likely confusing concrete object casting which will result in a "compile-time" error (e.g. if monkey were cast to "Child"), but that was NOT the example you provided. You in fact specifically called out the usage of interfaces, which will result in a "run-time" error. " :) "

                            Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet. The interesting thing about software is it can not reproduce, until it can.

                            1 Reply Last reply
                            0
                            • realJSOPR realJSOP

                              I don't like var. If it's so goddamn wonderful, why require its use at all? Why bother even defining types at all? If I wanted to code like that, I'd use VB.

                              ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                              -----
                              You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                              -----
                              When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

                              M Offline
                              M Offline
                              Mladen Jankovic
                              wrote on last edited by
                              #39

                              Type inference[^]

                              GeoGame for Windows Phone | The Lounge Explained In 5 Minutes

                              1 Reply Last reply
                              0
                              • Sander RosselS Sander Rossel

                                N_tro_P wrote:

                                I have found var is a religious argument

                                Sounds pretty religious to you. I've pointed out some scenarios where NOT using var may help in catching errors early and all you did is call me a failure and a bad programmer who doesn't know what he's doing and compare free MSDN server space to actual production environments. I actually checked if you were our regular troll, but you have a little too much rep for that. Seems you're just bad mannered. I'm quite done discussing this with you. I do use var though. Probably a lot more often than you don't :)

                                Read my (free) ebook Object-Oriented Programming in C# Succinctly. Visit my blog at Sander's bits - Writing the code you need. Or read my articles here on CodeProject.

                                Simplicity is prerequisite for reliability. — Edsger W. Dijkstra

                                Regards, Sander

                                J Offline
                                J Offline
                                Jeremy Falcon
                                wrote on last edited by
                                #40

                                Trust me, I've already learned that N_tro_P simply does nothing but call everyone stupid and argues. You can't win with someone on a podium thinking he's better than everyone. For what it's worth, I'm very pro var and I still agree with your points. I'll still use var personally, but I still agree with your points. So rest assured, there are pro var people out there that do listen. :-D

                                Jeremy Falcon

                                Sander RosselS 1 Reply Last reply
                                0
                                • Richard DeemingR Richard Deeming

                                  John Simmons / outlaw programmer wrote:

                                  Why bother even defining types at all?

                                  Because var doesn't mean "untyped". It means, "the type of this variable is obvious to the compiler, so I don't need to bother writing it".


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

                                  J Offline
                                  J Offline
                                  Jeremy Falcon
                                  wrote on last edited by
                                  #41

                                  Bingo!

                                  Jeremy Falcon

                                  1 Reply Last reply
                                  0
                                  • realJSOPR realJSOP

                                    I don't like var. If it's so goddamn wonderful, why require its use at all? Why bother even defining types at all? If I wanted to code like that, I'd use VB.

                                    ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                                    -----
                                    You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                                    -----
                                    When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

                                    J Offline
                                    J Offline
                                    Jeremy Falcon
                                    wrote on last edited by
                                    #42

                                    Don't confuse var with dynamic.

                                    Jeremy Falcon

                                    1 Reply Last reply
                                    0
                                    • J Jeremy Falcon

                                      Trust me, I've already learned that N_tro_P simply does nothing but call everyone stupid and argues. You can't win with someone on a podium thinking he's better than everyone. For what it's worth, I'm very pro var and I still agree with your points. I'll still use var personally, but I still agree with your points. So rest assured, there are pro var people out there that do listen. :-D

                                      Jeremy Falcon

                                      Sander RosselS Offline
                                      Sander RosselS Offline
                                      Sander Rossel
                                      wrote on last edited by
                                      #43

                                      Ahhh... The sound of reason, I've missed it in these parts :D I'm not pro-var and not anti-var, not sure how var I'll go :D

                                      Read my (free) ebook Object-Oriented Programming in C# Succinctly. Visit my blog at Sander's bits - Writing the code you need. Or read my articles here on CodeProject.

                                      Simplicity is prerequisite for reliability. — Edsger W. Dijkstra

                                      Regards, Sander

                                      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