Three Rules About Using Implicitly-Typed Variables

You can create an implicitly-typed variable using the var keyword.  The type is inferred, rather than declared.
Here are a few additional rules about using implicitly-typed variables.
Rule #1 - You can use var only for local variables
You can’t use var when declaring class fields/properties.
1
2
3
4
public class Person
{
    public var Height;    // Compile-time error
}
Rule #2 - You must initialize an implicitly-typed variable when you declare it
If you don’t initialize an implicitly-typed variable, the compiler can’t infer the type.
1
2
3
4
static void Main()
{
    var height;   // Error: Implicitly-typed local variables must be initialized
}
Rule #3 - You must declare implicitly-typed variables one at a time
You can’t declare more than one variable on the same line with var.


1
2
3
4
5
6
static void Main()
{
    int i, j, k;   // Declare three int variables
 
    var x, y, z;   // Error: Implicitly-typed local variables cannot have multiple declarators
}