It means that the type of the local being declared will be inferred by the compiler based upon its first assignment:
// This statement:
var foo = "bar";
// Is equivalent to this statement:
string foo = "bar";
Notably, var
does not define a variable to be of a dynamic type. So this is NOT legal:
var foo = "bar";
foo = 1; // Compiler error, the foo variable holds strings, not ints
var
has only two uses:
- It requires less typing to declare variables, especially when declaring a variable as a nested generic type.
- It must be used when storing a reference to an object of an anonymous type, because the type name cannot be known in advance:
var foo = new { Bar = "bar" };
You cannot use var
as the type of anything but locals. So you cannot use the keyword var
to declare field/property/parameter/return types.