views:

1635

answers:

5

I just installed a trial version of ReSharper and one of the first things I noticed is that it always suggests to replace explicitly typed local variables with implicitly typed ones, e.g:

public string SomeMethod(int aParam)
{
 int aNumber = SomeOtherMethod(aParam);
 // should be changed to:
 var aNumber = SomeOtherMethod(aParam);
}

I think explicitly typed variables are more readable (more explicit).

What do you think about ReSharper's suggestion? Is there any advantage in using implicitly typed variables? When do you use implicit/explict vars?

+1  A: 

It's just easier to type the var pseudo-keyword at times than a huge type name, especially if a generic could be involved. However, you should know they're functionally identical. There's no performance difference or anything either way. The compiler derives the type of the right-side of the assignment and replaces var with that type. It's not happening at run-time like a VB variant.

Daniel Henry
+4  A: 

There's a lot of discussion about this, but I think it all comes down to personal taste, just like using the 'this' keyword almost everywhere.

I personally prefer explictly typed variables, but when using nested generic collections things can become more readable using an implicitly typed variable. Look at:

Dictionary<string, Dictionary<string, string>> myDictionary = new Dictionary<string, Dictionary<string, string>>();

vs:

var myDictionary = new Dictionary<string, Dictionary<string, string>>();

EDIT: this SO topic covers the same topic, with some nice replies: http://stackoverflow.com/questions/236878/what-to-use-var-or-object-name-type

Razzie
+3  A: 

FWIW, the var keyword is plainly readable in many cases. Especially if...

  1. The right-side of the assignment is a constructor expression.

    var map = new Dictionary>();

  2. Local variables have good names.

HTH

Dustin Campbell
+3  A: 

I personally only use “var” when I can clearly distinguish the variable Type by just reading the declaration, for example:

var someVariable = new List<int>();

In the example above, its evident that “var” refers to “List<int>”.

I don’t like to use “var” when I have to go to some method definition to find out what variable type “var” represents or by having to rely on visual studio intelli-popup or whatever that is called, for example this in not ok to me:

var someVaraible = SomeMethod();

I mean, what is the “SomeMethod” function supposed to return? Can you tell just by looking at the line of code? No you can’t, so that is why I avoid using “var” on those situations.

Rene
A: 

Just in case some haven’t noticed yet, you can easily change the “suggestions” in Reshaper (Reshaper -> Options -> Languages -> Context Actions -> “Replace explicit type specification with ‘var’”).

I personally prefer to have explicit type specifications everywhere, but I'm not too fussy about it.

uli78