#803 – Situations When You Might Use the var Keyword

The var keyword allows you to avoid entering the full type of a variable, letting the compiler infer the type.  The variable is still strongly-typed, i.e. the type is known at compile time.

There is debate about when you should use var.  It’s use ends up dictated by coding style guidelines or personal preference.

You must use var when dealing with anonymous types because the compiler generates only an internal type name.

var myDog = new { Name = "Kirby", Age = 14 };

You might  use var when using LINQ, when the exact type of the query result is not apparent.

            var someDogs = from aDog in dogs
                          where aDog.Age > 10
                          select aDog.Name + "(" + aDog.Nickname + ")";

You might also use var to avoid having to repeat a type name that is already present in an expression.

            var dogs = new List<Dog>();