#806 – An Example of Mandatory Use of the var Keyword

When assigning the result of a query expression to a variable, there are cases when you do know the result type and so the use of the var keyword is optional.

However, in some cases, an anonymous type is created to contain the results of the expression.  In these cases, you must use the var keyword, because the correct type is generated internally by the compiler and not available to your code.

In the example below, we get something back that we can iterate on, but each element within the result set is anonymously typed, an object containing Name and Age fields.

            var oldDogs = from aDog in dogs
                                          where aDog.Age > 10
                                          select new { aDog.Name, aDog.Age };

            foreach (var anOldie in oldDogs)
                Console.WriteLine(string.Format("{0}, age {1}", anOldie.Name, anOldie.Age));
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 #806 – An Example of Mandatory Use of the var Keyword

  1. Pingback: Dew Drop – March 22, 2013 (#1,512) | Alvin Ashcraft's Morning Dew

  2. James Curran says:

    I think this demonstrates the problem I’ve had with this whole series of yours.

    Consider that the type here does not have to be anonymous. I could define a class (NameAndAge) and just by popping that one word into the expression, I no longing am REQUIRED to use var.

    Now, by the argument you made yesterday, I should now use:
    IEnumerable oldDogs = …

    But really, what has changed? Why do I need now to explicit be told the type oldDogs when I didn’t before?

    I generally use “var” except it the rare cases where I’m required to specify the type, and I’ve come to learn that, generally, you DON’T NEED to know the type in exact detail.

    This comes as a surprise to many developers (particularly adherents of Hungarian notation), but embrace “var” and you’ll see that it’s true.

    To further demonstrate this, consider yesterday, you said that it would be more clear as a IEnumerable. But clearly to who? The guy writing it already knows it’s an IEnumerable, and the guy maintaining it may be more concerned with it being an IQueryable or DataQuery or a WhereSelectArrayIterator any of which it can also be, depending on the type of “dogs”.

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: