The Var Keyword

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.

Advertisements

2 Responses to The Var Keyword

  1. Steven Suing says:

    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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: