To Var or Not To Var

This is obviously a highly debated topic that doesn’t have a clear right or wrong answer to it.  The use of the keyword var allows you to implicitly define a type.  An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.

For example:

var item = “table”;  //implicitely typed
string item = “table”; // explicitly typed

Some reasons that I have come across that people favor var for are that it reduces the amount of code and the time that it takes to code it. It makes sense; you use var, type your variable name and move on.  However, there are some drawbacks that can arise.  Say that you do not use a very descriptive variable naming.

var myCar = new Car(); //Clear
var i = myCar.GetSomething(); //Not Clear what i would be

So if I am a developer coming back to the code or it is within code I did not write, I am going to have to hover over it to see what exactly is returned. Time is ended up being saved in the coding aspect of it, but when bugs/enhancement/etc come up and the code goes through another read through time is lost deciphering types and variables due to poor naming conventions and var being used so loosely.

Linq does require var to be use when using on anonymous type.

var employeeQuery = from employee in company
                    where employee.Location == "USA"
                    select new { employee.Name, employee.Phone };

Since we are using an anonymous type, var is used.

However, say we have a type. Notice how it is a bit longer, but now I know exactly what my end result is and there is no question as to what the outcome is.

IEnumerable<Employee> employeeQuery = from employee in company
                                      where employee.Location == "USA"
                                      select employee;

It really seems to come down to is having a group standard from within your team.  Personally, I use explicit typing so that there is no question and I know exactly what type is going to be chosen at compile time.  As well, future developers will know exactly what my intent was and not have to try and guess what I was aiming for or simply being lazy.

Thoughts? What are your coding standards?


StackOverflow Profile