Except for non human readable code is there another reason not to use var for every variable in functions? I mean is it performance hit not to use int, SqlCommand, string but use var instead?
5 Answers
using or not using "var" does not change other observable characteristics of the program, such as its performance.
The question of whether or not to use "var" hinges upon its effect on the human readers and maintainers of the code, not on its effect upon the compiled artefact.
Hava a look at this excellent article: https://learn.microsoft.com/en-gb/archive/blogs/ericlippert/uses-and-misuses-of-implicit-typing
3 Comments
var MyCar = FirstCarFactory.MakeCar(); and later in the code, MyCar = SecondCarFactory.MakeCar();. If both factories return type ICar, the code will work find even if the object instances returned by factories are different types. On the other hand, the code would then require that the factories return type ICar rather than the specific type of object they produce. If the consumer code had instead said...ICar MyCar = FirstCarFactory.MakeCar();, it would have worked just fine even if the return type from the first car factory was ToyotaPriusHatchback instead of ICar. The need for specifying that the variable should be of type ICar rather than ToyotaPriusHatchback stems from the fact that it will be written someplace other than the declaration. Were it only written by the line that defines it, it would be just fine if MyCar were a ToyotaPriusHatchback.It's definitely not a performance hit. var isn't actually a type, but a placeholder in your code, that means "I don't want to write out the type of this variable." In fact, if you hover over the text in Visual Studio, it will show a tool-tip indicating the type that you decided was too long to write!
In all seriousness, though, you should generally use var when it's clear what the type is from the code, so that other aren't confused when reading it.
Comments
Yes, use var everywhere.
I love var. It's saved me loads of keystrokes. It helps me code in a "use first" fashion, and it makes refactoring more powerful.
It doesn't matter what the type is named. Intellisense tells me what the type can do, that is all that matters.
Even if I knew the type name, it wouldn't help me much if intellisense is broken, because I wouldn't necessarily know what a specific method or property is called just from the type name alone.
Some specifics where var makes things better:
- Calling a method (without knowing what it returns - especially if it is a generic type)
This one is big. I often don't remember what a method returns, but I know the name of that method. Having to pull the return type out of my head slows me down. I just write var, call the method with my inputs, and voila intellisense tells me what that return type is and what I can do with it.
// Imagine a method that creates a return type that gets some generic type from the call arguments Tuple<TA,TB,TC,TD,TE> Combine<TA,TB,TC,TD,TE>(TA a, TB b, TC c, TD d, TE e); // GOOD: Call this with var var combo = Combine( "Some text", 42, true, new Dictionary<int, List<string>>(), "Other text"); // BAD: Without var Tuple<string, int, bool, Dictionary<int, List<string>>, string> combo = Combine( "Some text", 42, true, new Dictionary<int, List<string>>(), "Other text"); - Refactoring a return type
If I use var, the compiler immediately tells me where that type is being misused (perhaps the new return type doesn't have the same property names).
If I didn't use var, I would just get an error about failure to assign the type. Then, I would have to go change that type to the new type (every single place it was called) and then I finally get the warnings where that type is being used incorrectly.
- Focus on naming variables rather than retyping type names.
var is one of the best things that ever happened to C#.
// BAD: No var Dictionary<int,List<Tuple<int,bool,string>>> ahhhhThatWasDifficult = new Dictionary<int,List<Tuple<int,bool,string>>>(); // GOOD: With var // I can think of a good name before writing this complex type var validNameCountDictionary = new Dictionary<int,List<Tuple<int,bool,string>>>(); If I still haven't convinced you, well you have no choice anyway if you want to use:
- Anonymous types
- Linq
So, why not go all the way and use var everywhere.
I know it's obscure, but I'll even do this sometimes just so I can always use var and have a consistent look to my code:
var number = (int?) null; Cause I love var.
P.S. I am a little sad that let is replacing var in Typescript/ES6, but Javasctipt var !== C# var
2 Comments
var other than convey lots of emotion about it. And I disagree that forcing the coder to think about changing types is always a bad thing. It depends on the culture of the codebase. The true value in using var everywhere is it makes types matter less, like a typeless language. That's it.There are rare / occasional cases when you are not declaring a variable at the same moment you retrieve a value for it. So var cannot effectively be used in these instances.
Example - calling a method which will act solely based on the type of an object passed to it.
Derived d = null; // there is nothing to infer the type from var someInfo = GetInfo(d); ... // Base is an ancestor of Derived Info GetInfo(Base b) { if (b is Derived) return ...; if (b is Derived2) return ...; ... } Perhaps alternately you could do:
var d = default(Derived); or
var d = (Derived)null; but neither is any more readable IMO. I wouldn't do that just for the sake of using var.
Comments
It's about implicit and explicit typing. C#.NET is a typed language, meaning that you define what type of data is stored in memory. If you don't define that, you make some operations less safe, so you want to type explicitly as much as possibly. However in some cases the type is really obvious from your code, so you can just leave it up to the compiler to figure out what type the variable should be, which is implicit typing.
A problem with not having types is that in memory, which is essentially a bunch of 1's and 0's this data could mean anything, so if you originally put in an integer at location 000001 and then later try to read it as Cat (just imagine that being some type), then nothing of what you just read out from memory will make much sense. So that is the reason that a type system was invented, to tell you what data you are storing where and to make sure that you read data back in a way which can be understood again by humans, as for a machine it doesn't really matter at the end of the day what the data is.
6 Comments
var does not do away with types. It only makes the compiler pick the right type for you. if you say var foo = bar(), then foo will still be strictly typed, only you don't need to type the type. (Pun not intended, but noted.)var is exactly the same as explicit types. What do you mean that some operations are "less safe"?