I wrote this article original to give som guidelines for my company, Oxygen Software. Therefore its my view on the var keyword.
Use it wisely
The var keyword in c# has made it easier to be a developer, it also improoves the readerbility of your code, when used correctly. When used wrong itll confuce the developer more than ever. this will give a few guidelines for where you can use the var keyword, and where you should not use it.
You should only use the var keyword when you have given some thoughts into the question "Is it clear which type my varialbe is?", if the answer to the question is yes, you can use the var keyword, if the answer is no, you probably shuoldnt use the keyword.
// There is no question of what type the variable list is containing var list = new List < string >(); // variable customer is type customer var customer = new Customer();
// No one knows what type the variable someVariableName is var someVariableName = SomeMethod(); // what type is FirstProperty? var someVariableName = myObject.FirstProperty;
the above examples are quite simple, but should give you a hint of what direction you shuold use your var keywords.
Another important aspect is to always give your methods proper names, imagine the following:
List<Customer> customers = CustomerPersistence.GetCustomerListByAreaCode(5000);
In this example, the method name gives you no doubt that its returning a list of customers, therefore you can use the var keyword
var customers = CustomerPersistence.GetCustomerListByAreaCode(5000);
It'll also increase readerbility when having classes that have very long names like this:
List<CustomClassHavingVeryLongName> customers = CustomClassHavingVeryLongNamePersistence.GetCustomClassHavingVeryLongNameList();
Where you easily can use the var keyword to make it more readable
var customers = CustomClassHavingVeryLongNamePersistence.GetCustomClassHavingVeryLongNameList();
The var keyword was introduced together with LINQ, and this is where the keyword can be a little confusing. In LINQ youll have alot of var-variables that contains some kind of IEnumerable<T>. This is ok, as its the way LINQ was ment to be.
var results = from r in dataContext.SomeTable select r;
I Guess the main point is that other people that will look at your code, shouldnt be in doubt what type a variable is containing, use var if its clear, use its real type, if its not
Please feel free to comment the above :-)