Using implicitly typed local variables

C#Coding StyleImplicit Typing

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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: https://stackoverflow.com/questions/236878/what-to-use-var-or-object-name-type

EDIT2: Working a lot with async nowadays, I find that using explicity typed variables can sometimes prevent nasty bugs. Consider this silly example where you would want to return the Id of a user. Also consider that GetUserAsync returns a Task<User>. If you use implicitly typed variables, you would end up using something like this:

public long GetUserId()
{
  var user = GetUserAsync();
  return user.Id;
}

This compiles, but it is wrong. 'user' is actually a Task<User>. And it compiles as Task also has an Id property. In this case, one would accidentally return the Id of a Task instead of the User.

public long GetUserId()
{
  User user = GetUserAsync();
  return user.Id;
}

The above does not compile, as the compiler will complain that you cannot cast a Task to a User. Adding the await keyword of course solves this.

I've actually had this happen to me once :-)

Solution 3 - C#

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.

Solution 4 - C#

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.

Solution 5 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionM4NView Question on Stackoverflow
Solution 1 - C#ReneView Answer on Stackoverflow
Solution 2 - C#RazzieView Answer on Stackoverflow
Solution 3 - C#uli78View Answer on Stackoverflow
Solution 4 - C#Daniel HenryView Answer on Stackoverflow
Solution 5 - C#Dustin CampbellView Answer on Stackoverflow