Don’t overuse var keyword

Most of the Linq demos that are around show sample query expressions like this (the demos shown are largely from the 101 samples included with the May 2006 CTP):

int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

var lowNums = from n in numbers

              where n < 5

              select n;

The point of this posting is that I believe that you shouldn’t overuse the var keyword in cases where you know the shape of the result. The shape might be the concrete or base type of the object reference, or one of the interfaces that it implements.

In the sample above you know that the result of the query expression will be IEnumerable<int>. This is because the Select operator returns IEnumerable<T> and the source of the data is int[] (to be precise it is already IEnumerable<int> after the Where operator). So, why not be more explicit and express that in the declaration of lowNums:

int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

IEnumerable<int> lowNums = from n in numbers

              where n < 5

              select n;

int[] lowNums2 = (from n in numbers

              where n < 5

              select n).ToArray();

Admitted, later versions of Visual Studio should be able to give IntelliSense (like Don Box says: the most addictive drug since crack) information on var declared variables. But, var is really meant for situation where you create projections. You can instantly recognize those situations because an anonymous type is declared. 

string[] words = { “aPPLE”, “BlUeBeRrY”, “cHeRry” };

var upperLowerWords = from w in words

                select new {Upper = w.ToUpper(), Lower = w.ToLower()};

This is what var is meant for: anonymous types. Yes, it can be used by lazy developers to save some typing. I encourage you to try and keep that to a minimum. It will make your code more readable.

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s