The Var Keyword
March 8, 2011 2 Comments
Consider the following block of code:
using (NorthwindEntities entities = new NorthwindEntities()) { var x = from y in entities.Categories select y; }
The Var keyword resolves at run-time, meaning that its value depends on the right hand side of the equation. If I chain a function on the right hand side like this, var takes on a different meaning:
using (NorthwindEntities entities = new NorthwindEntities()) { var x = (from y in entities.Categories select y).First(); }
I see that var is used extensively, so I guess I am in the minority but I don’t like to use it. I am willing to trade off some verbosity for clarity of intention. If I use the var keyword, I need to read the right hand side of the equation first to figure out what goes in it (and hope that I guessed correctly – with some of the convoluted LINQ that I have seen written, no small task). Since I read left to right, it waste time and my CPU cycles. In addition, I fail to see what is wrong with being more explicit in the left hand side of your equation:
using (NorthwindEntities entities = new NorthwindEntities()) { IQueryable<Category> catagotyQuery = from catagories in entities.Categories select catagories; }
In this example, my intention is clear and I have much more readable and maintainable code.
I really enjoyed your blog posts. This statement is incorrect “var keyword resolves at run-time”. var is static typed – the compiler and runtime know the type.
However, I partially agree with your premise that its easier to read using explicit typed variables, but not in the example you give. The reason for this is that LINQ is so prevalent that I can look at it and know exactly what will be return. The example this where I think explicitly typed variables is most important is when setting it from a function like var categories = db.GetClient(); In the case of the function the type is completely hidden away and cannot be ascertained by the code on the right.
You are right – I confused it with the variant keyword from the VB6 days….