tags:

views:

810

answers:

12

Resharper certainly thinks so, and out of the box it will nag you to convert

Dooberry dooberry = new Dooberry();

to

var dooberry = new Dooberry();

Is that really considered the best style?

+1  A: 

I have a feeling this will be one of the most popular questions asked over time on Stack Overflow. It boils down to preference. Whatever you think is more readable. I prefer var when the type is defined on the right side because it is more terse. When I'm assigning a variable from a method call, I use the explicit type declaration.

John Sheehan
+29  A: 

It's of course a matter of style, but I agree with Dare: C# 3.0 Implicit Type Declarations: To var or not to var?. I think using var instead of an explicit type makes your code less readable.In the following code:

var result = GetUserID();

What is result? An int, a string, a GUID? Yes, it matters, and no, I shouldn't have to dig through the code to know. It's especially annoying in code samples.

Jeff wrote a post on this, saying he favors var. But that guy's crazy!

I'm seeing a pattern for stackoverflow success: dig up old CodingHorror posts and (Jeopardy style) phrase them in terms of a question.

Jon Galloway
Why not fix the name of the variable instead of complaining about var? var userID = GetUserID();It is not actually very important if userID is string or int, it is something that identify user and should be accepted by relevant functions.
Ilya Ryzhenkov
A: 

"Best style" is subjective and varies depending on context.

Sometimes it is way easier to use 'var' instead of typing out some hugely long class name, or if you're unsure of the return type of a given function. I find I use 'var' more when mucking about with Linq, or in for loop declarations.

Other times, using the full class name is more helpful as it documents the code better than 'var' does.

I feel that it's up to the developer to make the decision. There is no silver bullet. No "one true way".

Cheers!

OJ
A: 

No not always but I would go as far as to say a lot of the time. Type declarations aren't much more useful than hungarian notation ever was. You still have the same problem that types are subject to change and as much as refactoring tools are helpful for that it's not ideal compared to not having to change where a type is specified except in a single place, which follows the Don't Repeat Yourself principle.

Any single line statement where a type's name can be specified for both a variable and its value should definitely use var, especially when it's a long Generic< OtherGeneric< T,U,V>, Dictionary< X, Y>>>

Mark Cidade
A: 

There was a good discussion on this @ Coding Horror

Personally I try to keep its use to a minimum, I have found it hurts readability especially when assigning a variable from a method call.

Aros
A: 

@jongalloway - var doesn't necessarily make your code more unreadable.

var myvariable = DateTime.Now
DateTime myvariable = DateTime.Now;

The first is just as readable as the second, and requires less work

var myvariable = ResultFromMethod();

here, you have a point, var could make the code less readable. I like var because if i change a decimal to a double, i don't have to go change it in a bunch of places (and don't say refactor, sometimes i forget, just let me var!)

EDIT: just read article, i agree. lol.

Darren Kopp
A: 

One of the advantages of a tool like ReSharper is that you can write the code however you like and have it reformat to something more maintainable afterwards. I have R# set to always reformat such that the actual type in use is visible, however, when writing code I nearly always type 'var'.

Good tools let you have the best of both worlds.

John.

John Richardson
A: 

There's a really good MSDN article on this topic an it outlines some cases where you can't use var:

The following restrictions apply to implicitly-typed variable declarations:

  • var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.
  • var cannot be used on fields at class scope.
  • Variables declared by using var cannot be used in the initialization expression. In other words, this expression is legal: int i = (i = 20); but this expression produces a compile-time error: var i = (i = 20);
  • Multiple implicitly-typed variables cannot be initialized in the same statement.
  • If a type named var is in scope, then the var keyword will resolve to that type name and will not be treated as part of an implicitly typed local variable declaration.

I would recommend checking it out to understand the full implications of using var in your code.

lomaxx
+4  A: 

I use it only when it's clearly obvious what var is.

clear to me.

XmlNodeList itemList = rssNode.SelectNodes("item");
var rssItems = new RssItem[itemList.Count];

not clear to me.

var itemList = rssNode.SelectNodes("item");
var rssItems = new RssItem[itemList.Count];
sieben
A: 

I'm seeing a pattern for stackoverflow success: dig up old CodingHorror posts and (Jeopardy style) phrase them in terms of a question.

I plead innocent! But you're right, this seemed to be a relatively popular little question.

serg10
+4  A: 

The best summary of the answer I've seen to this is Eric Lippert's comment, which essentially says you should use the concrete type if it's important what the type is, but not to otherwise. Essentially type information should be reserved for places where the type is important.

The standard at my company is to use var everywhere, which we came to after reading various recommendation and then spending some time trying it out to see whether the lack of annotated type information was a help or a hindrance. We felt it was a help.

Most of the recommendations people have linked to (e.g. Dare's one) are recommendations made by people who have never tried coding using var instead of the concrete type. This makes the recommendations all but worthless, because they aren't speaking from experience, they're merely extrapolating.

The best advice I can give you is to try it for yourself, and see what works for you and your team.

Greg Beech
+1  A: 

It only make sense, when you don't know the type in advance.