var
is useful for anonymous types, which do not have names for you to use.
var point = new {X = 10, Y = 10};
This will create an anonymous type with properties X and Y. It's primarily used to support LINQ though. Suppose you have:
class Person
{
public String Name {get; set;}
public Int32 Age {get; set;}
public String Address {get; set;}
// Many other fields
}
List<Person> people; // Some list of people
Now suppose I want to select only the names and years until age 18 of those people who are under the age of 18:
var minors = from person in people where person.Age < 18 select new {Name = person.Name, YearsLeft = 18 - person.Age};
Now minors
contains a List
of some anonymous type. We can iterate those people with:
foreach (var minor in minors)
{
Console.WriteLine("{0} is {1} years away from age 18!", minor.Name, minor.YearsLeft);
}
None of this would otherwise be possible; we would need to select the whole Person object and then calculate YearsLeft in our loop, which isn't what we want.