Using implicitly typed local variables

M4N picture M4N · Mar 16, 2009 · Viewed 37.8k times · Source

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?

Answer

Rene picture Rene · Mar 16, 2009

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.