#204 – Three Rules About Using Implicitly-Typed Variables
January 7, 2011 1 Comment
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.
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.
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.
static void Main() { int i, j, k; // Declare three int variables var x, y, z; // Error: Implicitly-typed local variables cannot have multiple declarators }