tags:

views:

3326

answers:

34

C# 3.0 introduces implicitly typed variables, aka the "var" keyword.

var daysInAWeek = 7;
var paul = FindPerson("Paul");
var result = null as IPerson;

Others have asked about what it does or what the problems with it are:

I am interested in some numbers - do you use it? If so, how do you use it?

  1. I never use var (and I never use anonymous types)
  2. I only use var for anonymous types
  3. I only use var where the type is obvious
  4. I use var all the time!
A: 

3 - I just used var in a situation where it was obvious. The code looked something like this:

List<ErrorCodes> errors = AttemptMethod();
foreach (var errorCode in errorList) {
    // error handling code
}
Travis
+12  A: 
JaredPar
Jared, what specific additional steps do you take to be more friendly for type inference?
Paul Stovell
Great answer. I was doing similar things, but my implementations were too naive compared to these. Thanks a lot, very useful code. I wish I saw you utility library earlier, too.
Roman Boiko
+1  A: 

While using var makes writing code faster, I find myself explicitly typing my variables, still. Obviously you have to use it for anonymous types, so I'll use it there.

Hence, my answer is: 2

Kyle Trauberman
+72  A: 

4 - I'm a var whore, I use var everywhere.

The only time I don't use var is when I'm defining a new method/ class so I don't have to change it from object later on.

I find that var makes my life a lot easier when I do refactoring, especially when used within foreach loops.

Slace
I wish 1.1 had var...
John Baughman
I'm glad I'm not the only one... I've been feeling dirty for using it so much, but no longer!
Daniel Schaffer
I'm glad I don't work on your code.
Yuriy Faktorovich
OMG a var whore that's a good one im too!!
Shimmy
@John Baughman - I weep for you my friend! I haven't touched 1.1 in a long time and I don't miss it at all!!!
Sohnee
+1  A: 

I'm going for 3.

There are times when its kind of silly, and there are times when it makes sense.

If you're using it to replace say int, then it doesn't make much sense. You're not really benefiting, your using var just to use it, it's still three letters. If you're using it to infer an iterator or for a LINQ query or when you know what the method returns and it makes the code fit in the visible area of the code editor, cool.

Not mention the fact that if you're experimenting with LINQ and you keep getting compiler errors because your query goes from returning an IEnumerable<T> to IQuerable<T> to List<T>, then you're wasting your time.

Honestly, If you've ever used languages (like C++) which don't have type inference (not including TR1) it can make code where you use vectors painful to read because you send most of your time scrolling the code into view.

EDIT: Yes, in TR1 the C++ team re-purposed the auto keyword, let rejoice in the love!

Chris
the new c++ will have the "auto" keyword i believe, which does the same thing as "var".
Paul Stovell
@Paul: yes, TR1 or `Technical Release 1` includes it.
Chris
+35  A: 

Yes, definitley. Consider this:

Dictionary<int,Tuple<int,string>> items = new Dictionary<int,Tuple<int,string>>();

and then this:

var items = new Dictionary<int,Tuple<int,string>>();

The latter is much better IMO. For a start it doesn't require a scroll bar to be viewed!

I'm probably a 3.5.

Jonathan Parker
yup, the less punctuation your eyes stumble over the better
Chris
+1  A: 

I'm more of a type 2 guy - for clarity when reading code, I prefer to explicitly state the type whenever possible. Sure, in the IDE we have Intellisense and all - but how about on a printout?

Whenever possible, try to be as explicit as possible - makes reading code easier for other guys who come in and have to understand your code later on.

Marc

marc_s
var e = new IEnumerable<string>(); Is there any doubt what the type of e is? Do you _really_ need the second type declaration?
Adam Lassek
Yes, I would strongly suggest to use the EXPLICIT type whenever possible - it's just cleaner, clearer. If it doesn't cost you any effort, express your intent explicitly. It helps down the line.
marc_s
I don't understand your definition of explicit in this case. Writing the type declaration a second time doesn't give you any more information.
Adam Lassek
Yes it does - it clearly states that you want a string - if you suddenly change something and you assign something else, you at least might get a compiler warning/error.Be as explicit as possible - it only costs you three extra characters here....
marc_s
I still don't understand what you mean. In my example, I'm already clearly defining that I'm initializing an IEnumerable<string>. The constructor for IEnumerable<string> will never give me anything else. Repeating the type declaration a second time adds no information.
Adam Lassek
Well, coming from a Pascal background, I'm always in favour of CLEARLY specifying what you want. Say you have IEnumerable<string> and expect that - suddenly you apply .First() clause to it and you get back a single string - no longer an IEnumerable. Clearly saying what you want / expect is helpful.
marc_s
Point taken; specifying the type when the right side of the assignment isn't perfectly clear is not redundant. But, this is not the example I gave. Specifying the type is good when it's being assigned from a non-generic function, but there are still many cases where it's pointless duplication.
Adam Lassek
@Adam Lassek: A small typo: one can't use ` new IEnumerable<string>()`, because it can't be instantiated (it is an interface). `List<string>()` **can**. Sometimes I want to make my variable `IEnumerable<T>` and assign to it an instance `List<T>()`. For example, when I need to store the `IEnumerator<T>`. One of such cases is described here: http://msmvps.com/blogs/jon_skeet/archive/2010/07/27/iterate-damn-you.aspx
Roman Boiko
A: 

I`d like to use it whenever it's possible(because I do not use it frequently), but is there any performance problem?

no, the compiler completely optimizes it out - including in the "null as IPerson" version I showed.
Paul Stovell
what about for intellisense and visual studio? if I had 100,000 lines of code littered with vars will my IDE hang trying to figure all this out as I go?
BPAndrew
@BPAndrew: IntelliSense doesn't spend more time on `var` that on explicit type declaration. It needs to figure out the type of the right-hand side of assignment, regardless of whether you use `var` or not.
Roman Boiko
+6  A: 

I've read/heard a lot of people advising that you shouldn't abuse var because the type is vitally important to code readability.

For example:

IFoo f = GetMeSomething();
DoSomething(f);

Using var supposedly makes it less readable:

var f = GetMeSomething();
DoSomething(f);

Now we don't know what f is, which is supposed to be bad.

And yet no one would ban function composition:

DoSomething(GetMeSomething());

The sky doesn't fall in every time someone does that. Also lambdas have built-in type inference:

list.ForEach(f => DoSomething(f));

So it may be that over time, people get used to the idea of using var by default and only avoiding it where there really is a good reason.

Or maybe it will be like "Methods should only have one exit" and hang around in coding standards for decades, for no good reason. Another one of these is "Lambdas should be no more than two lines long."

Personally I hardly every use var but only for "cultural" reasons (i.e. to avoid starting arguments), because the benefit is usually minor. For example, someone said above that there's no point using var instead of int because they're the same number of characters to type. Not so - if you have a bunch of code using int and later you decide to use double, it saves you a few seconds of search and replace!

Daniel Earwicker
"using var by default" - Hell, yes! And while we're on it, let's drop type safety altogether and let the compiler figure it out? :)
Markus
@Markus - just in case you're not joking: this isn't dropping type safety. In fact, if you use `var` in a `foreach` loop, you may *increase* type safety.
Daniel Earwicker
@Daniel - Definitely a joke. :) Although a slightly bitter one, I mean, we've got `dynamic` now ... :)) To be honest, I'm really not a fan of the idea to use var for anything else than anonymous types, or maybe two-liners. People argue about ultra long type names, but that's a thing that can be fixed with a using in a second. Same for the old IDE argument: While it may be true that you can see the type thanks to IntelliSense, this doesn't work on paper or when looking at a diff. I really think that if one knows the type, one should write it down. That's what it's for.
Markus
@Daniel - That said, I liked your answer. I don't agree with it, but it made me think about my point of view.
Markus
A: 

i'm a 3 as i think that writing var is muuuch more convenient than having ultra long declarations with namespaces, multiple generic definifinitions and so on.

Joachim Kerschbaumer
+1  A: 

I'm only using var when I dealing with LINQ.

ecleel
+1  A: 

Somewhere in between 2 and 3. It's handy for some things regarding to data-access (e.g. entity framework). But, when ever possible I try to use it where the resulting type is obvious or at least you get it with a small amount of thought...

Sascha
A: 

Actually, i'm more of a 2.5 guy.

2.5 - I only use var when the type isn't very obvious, or when I don't really need to think about the type.

I seem to use it primarily with LINQ to SQL. ie.

var results = from blah ....

Honestly, i'm not a big fan of big honking types. You can use a using to alias them, but that's doing the same thing.

And I absolutely HATE interfaces as variable types.

Mystere Man
"And I absolutely HATE interfaces as variable types." Wuh?
Daniel Earwicker
just a personal preference. Of course I can't change the actual type, but I can hide it from my eyes when i'm coding by using var ;)
Mystere Man
+1  A: 

I'm a 2.

I only use var when dealing with LINQ to SQL.

Otherwise I don't really like making the compiler decide the type for my object.

Eibx
+1  A: 

I think I am a 2.5

I usually only use var for anonymous types but I also use it sometimes for Linq queries where the resulting type may change if I change the query later. Then I also use var so I have less refactoring to do when I change the retunr type of the select.

Sruly
+4  A: 

3, but I find 'obvious' to be highly subjective.

I've found most devs are ok with:

var sb = new StringBuilder();

But get annoyed by:

List<MyType> items = GoGetMyTypes();

foreach ( var item in items ) {
    //they don't know what item is here without intellisense.
}
Keith
I get annoyed in your second example when it is: var items = GoGetMyTypes(). That's really impossible without intellisense. As your second example stands, I'd have no problems with that.
John Kraft
I don't understand these "don't know the type without intellisense" arguments. Even free open-source C# IDE's have intellisense these days. It's like saying, "I don't know what type it is unless I can see." You can see. "Oh yeah." And don't start with the dead-tree code reviews, that's just silly.
Joel Mueller
If you're getting a set of MyType objects, why would you call what you get back "items"? If you call it something useful ("myTypesWithActiveCustomers" or whatever), then there's no problem with saying foreach(var item in myTypesWithActiveCustomers).
Kyralessa
@Kyralessa - maybe, but if I'm only using it across a few lines I tend not to bother with such long names.
Keith
Well, if you're going to use non-obvious variable names, then it shouldn't be surprising that the use of var leaves things non-obvious.
Kyralessa
Honestly, it's great that we all have so nice IDEs. Now assume for a second that we look at a diff output from our version control. It's fine I may understand from the variable name that this is some kind of "customer" we're talking about, but still I have no clue what type it is.
Markus
Using `var` in `foreach` is by far the best option. Suppose the loop variable `item` was declared to be of type `MyType`. A future maintainer could change `items` to be of type `List<object>` and the program would still compile just fine! You only find the problem at runtime, when someone puts a `string` on the list of items and the `foreach` throws an exception. This is because `foreach` was in the language before generics, so it has to insert a silent cast. Hence is not type safe. If you make the loop variable a `var`, you disable the silent cast and restore the language to static safety.
Daniel Earwicker
+40  A: 

Personally, I only ever use var for anonymous types. Basically, when I have to use var rather than an explicit type.

I dislike the use of var for implicitly inferring types which can just as easily be explictly declared, i.e. :

// Yes, it's obvious that i is an int!
var i = 10;

// But why not use "int i = 10;".  Just as many characters to type!
int i =10;

Also, there are some situations where typing of the var is not obvious, at least not to me, i.e.:

var q = SomeFunkyMethodThatReturnsSomething();

Hmm.. Now I have to look up SomeFunkyMethodThatReturnsSomething in order to find out it's return type before I can know what q will be. Yes, intellisense can help, but I shouldn't have to rely on that, nor should I have to perform additional steps in order to know what type q is.

Here's another (admittedly contrived example) of where this kind of typing can be confusing:

double d = 0;
var e = 0;

I don't know about you, but this makes me have to do a double-take (excuse the pun!). At first glance, due to the "code noise" if you like, it's not immediately obvious what e is here. I have to stop and think before realizing that e is an int.

CraigTP
Also refactoring shouldn't be a problem when not using var either, Resharper atleast will help you through it with great ease.
Oskar Duveborn
@Oskar - Very good point about the refactoring. I personally consider the use of var when its not absolutely necessary to be a "code smell".
CraigTP
Sure, if you're defining an int there's no point in using var; but most type declarations are a lot longer. If you're defining an IEnumerable<T>, or a DataContext, var saves a lot of keystrokes and redundancy.
Adam Lassek
@Adam - I don't disagree with you when the type is something with a long name (ie. IInterface<Func<Type, Type>> etc.) however, for me it's a toss up between a few extra keystrokes and increased readability. I go for readability everytime. Extra keystrokes isn't that bad. We are coders after all!
CraigTP
I'm with you on readability, I just don't consider redundancy to be beneficial to that. I think one type declaration per line is plenty.
Adam Lassek
I consider NOT using var when you could to be a code smell. Well, that's an exaggeration, but really I think var helps readability more often than it hurts it.
Joel Mueller
I don't think that var can be comfusing.double d = 0;var e = 0D;var myDecimal = 4.35M;It's self explained.
Jonathan Shepherd
*"Now I have to look up SomeFunkyMethodThatReturnsSomething"*Uh, no you don't. Just hover over `q` and the tooltip shows you exactly what the type of `q` is.
mattmc3
+1  A: 

I'm at least a 3 (force of habit means I still type the type sometimes), for the reasons people have given above.

Having played with functional languages such as OCaml and Haskell, I'm quite happy with type inferencing - if anything C# doesn't go far enough!

Dave Warry
+10  A: 

1# here - aka "bah humbug, you crazy kids and your vars". back in my day we typed out all our types and we liked it just fine

BPAndrew
+1 for the comedy.
Jon Tackabury
It's funny because type inference is really old!
Matt Olenik
+2  A: 

I'm in camp #3. I prefer to use var when I feel it's obvious what the type is going to be. If I feel there is some ambiguity over it, then I'll be explicit.

Wayne M
A: 

VOTE : 3

But let me state that I explicitly define my variables. I let Resharper convert them to var when I clean the code. I am just not used to type var, but I use them ;-)

lucian.jp
A: 

5) I only use var where the type is NOT obvious.

When using various interfaces (whether the interface type OR an abstract type), and if you even care to know, it can sometimes be a burden to determine at design time what type will be inferred and where it can be used down the line. One would hope the Liskov Principle would come into play here, but it doesn't always unfortunately.

I read on an MSDN blog (the specific one escapes me) to use var when you're not sure polymorphically what type will be coming back. So basically, if I know what it's going to be, and I'm not typing a bunch of generic type details out (as in Jonathan Parker's example above), then I use the specific type. Otherwise, I use var.

My humble $0.02

Boydski
A: 

I'm a 3.5, or higher. There are some times that I don't use var, so I'm not quite a 4. I believe that redundancy is a worse problem than any readability hit. The redundancy that comes from restating the type over and over makes refactoring harder and just makes the code base more difficult to work with. There is already enough friction for developers to overcome as it is.

Charlie Flowers
+1  A: 

I'm a 1-2. I think the simple case is that over the longer term, the var keyword will have been seen to have weakened the language, because it inherently makes code harder to read, especially after 1 or 2 years. I've worked in several software houses already which have added var as a prohibited keyword, except in very specific instances, to enforce explicit declaration, and to improve long term readability. It should really be only used when your not sure when the rvalue return type is going to be, and intellisense doesn't immediately offer it up. Otherwise use sparingly.

scope_creep
+1  A: 

I tend to use a lot of generics in my code,...as well as lambda expressions, and the like.

So yes, I use var everywhere I can.

Once you get over hungarian notation, switching to var is easy.

Chris Brandsma
+1  A: 

I use var with anonymous types in LINQ and in production code sometimes when the type is obvious from right side value.

In some tests and prototypes the var is very handy.

Jozef Izso
+1  A: 

3 for me. I use it everywhere the type is obvious. Why on earth would anyone want to type the same thing twice, especially when generics with multiple type parameters are involved? :)

Mark Simpson
+4  A: 

My standard is that the only time var is okay is with LINQ, anonymous types, and

var foo=new Something();

This is not okay:

var bar=GiveMeSomething();
Zifre
+1 for disliking bar. :D (Jokes aside, I fully agree with this.)
Markus
+2  A: 

I use var whenever possible. I find this invaluable for refactoring. I can change the return type of a method without having to change any of the methods that call it (in most cases).

I had an issue like this with code that returned List. The recommendation from FxCop was to use Collection or ReadOnlyCollection for these. Before making this refactoring, I first had to change all the explicit references to use var. Then, changing the return types made little or no change to the calling code.

John Saunders
+3  A: 

We've discussed this at my current job, where the feeling among some is that it's OK to use var where the type is immediately obvious.

I seem to be in the minority, but I disagree. Why? Because I think having a type doesn't actually convey that much information. The name of the variable conveys much more. The real problem with using var everywhere is that it uncomfortably reveals the fact that you're choosing crappy names for your variables.

The solution, of course, isn't to ban var; it's to allow var everywhere and fix the variable-naming problems that become obvious when you do.

Kyralessa
A: 

I use it only in LINQ queries, because i don't have to check the return type. Sometimes i use var in foreach loops, because of same reason. Otherwise is better using types.

Jan Remunda
+1  A: 

I'm a huge fan of var simply because it looks so much nicer.

We work all the time to reduce repeated functionality (refactoring) but people seem to support this repeated declaration of types. Apart from convention, there's no need to declare the type on both sides of the equals sign.

var things = new List<int>();
List<int> things = new List<int>();

I prefer to use var when I can.

Having said that, I'm now working in an environment where a support team need to quickly analyse code and apparently do so in text editors rather than booting up Visual Studio. Therefore they have no Intellisense. Using var definitely doesn't make things clearer for the support team; if programmers are used to seeing the type declared first then they may be confused, especially when working under pressure at 3am. So I do see an argument for avoiding the use of var.

Kirk Broadhurst
A: 

To some extent I think that as developers we look for a nice rule that we can apply across the board.

The correct answer to the famous "var debate" is that it should be used when appropriate. We're paid the big bucks because we can determine when to use things such as "var" and when to avoid using them.

I believe that the use of "var" can be more extensive than just for anonymous types - but using it absolutely everywhere suggests that not enough thought is going into its use.

Sohnee
A: 

2 - I only use var for anonymous types.

In many cases the use of var makes the code less readable, especially when used to store method results.

jswanson