If the compiler can infer the type from the initialization expression, we can use the keyword
var
to declare variable type.
For example:
var x = "hello";
var y = new System.Text.StringBuilder();
var z = (float)Math.PI;
This is equivalent to:
string x = "hello";
System.Text.StringBuilder y = new System.Text.StringBuilder();
float z = (float)Math.PI;
Implicitly typed variables are statically typed.
For example, the following generates a compile-time error:
var x = 5;
x = "hello"; // Compile-time error; x is of type int