Local Variable Type Inference

Local Variable Type Inference

Local variables can be given an inferred “type” of var instead of an explicit type. The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement. The inferred type may be a built-in type, an anonymous type, a user-defined type, or a type defined in the .NET Framework class library

With this feature, the type of the local variable being declared is inferred from the expression used to initialize the variable. This is achieved using the var keyword (familiar to those who work with scripting languages, but actually it is quite different). It allows us to write the following code:


var num = 50; 
var str = "simple string";
var obj = new myType();
var numbers = new int[] {1,2,3};
var dic = new Dictionary<int,myType>();

The compiler would generate the same IL as if we compiled:

int num = 50; 
string str = "simple string";
myType obj = new myType();
int[] numbers = new int[] {1,2,3};
Dictionary<int,myType> dic = new Dictionary<int,myType>();

Note that there is no un-typed variable reference nor late-binding happening, instead the compiler is inferring and declaring the type of the variable from the right-hand side of the assignment. As a result, the var keyword is generating a strongly typed variable reference.

Previous ArticleNext Article