#805 – An Example of Discretionary Use of the var Keyword

Below is one example where you may or may not want to use the var keyword.

            var oldDogs = from aDog in dogs
                          where aDog.Age > 10
                          select aDog.Name;

            foreach (var next in oldDogs)
                Console.WriteLine(next);

This works just fine.  We don’t specify the type of the value returned from the query expression, but we know that it’s something that we can iterate on, so we just use var for the result and then var again in the foreach.

The difficulty comes when someone else is going to modify this code.  The query actually returns an enumerable list of strings.  But reading the code, you might make the mistake of thinking that it returns a list of dogs.

We could have been more clear by writing:

            IEnumerable<string> oldDogs = from aDog in dogs
                          where aDog.Age > 10
                          select aDog.Name;

            foreach (string name in oldDogs)
                Console.WriteLine(name);
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 Responses to #805 – An Example of Discretionary Use of the var Keyword

  1. Eric Olsson says:

    I’ve found that if you are careful about choosing variable names, that the use of var does not become a problem.

    In this example, I would prefer the variable oldDogsNames which helps avoid the assumption that you have Dog objects instead of just strings.

  2. Matt Freiburg says:

    Or by giving it a more comprehensively descriptive variable name – i.e. oldDogsNames instead of oldDogs.

    IMHO, variable naming is the most under-appreciated element in contributing to one’s code maintainability. Don’t get me wrong, now. I’m not advocating getting all crazy-like and using “lang_Hungarian abbr_Notation”.

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: