var versus concrete type usage

KrishnaDhungana picture KrishnaDhungana · Dec 5, 2013 · Viewed 20.5k times · Source

I have checked 5 or more post in stackoverflow regarding var usage but I am still looking for an answer regarding var usage. I am used to use Concrete type instead of var, but my Resharper complains to change to var. Is var a choice of type - even when concrete type is known?

Answer

gpmurthy picture gpmurthy · Dec 5, 2013

The following is an extract from msdn...

The var keyword can also be useful when the specific type of the variable is tedious to type on the keyboard, or is obvious, or does not add to the readability of the code. One example where var is helpful in this manner is with nested generic types such as those used with group operations. In the following query, the type of the query variable is IEnumerable>. As long as you and others who must maintain your code understand this, there is no problem with using implicit typing for convenience and brevity.

However, the use of var does have at least the potential to make your code more difficult to understand for other developers. For that reason, the C# documentation generally uses var only when it is required.

Reference: http://msdn.microsoft.com/en-us/library/bb384061.aspx

Good Luck!