McCook Software.com

All men by nature desire knowledge. -- Aristotle

Everything should be made as simple as possible, but not simpler.

-- Albert Einstein --

Local Type Inference

Type inference refers to the ability of a programming language to automatically deduce a variable’s type. Local type inference is available starting with C# 3.0 and Visual Basic 9.0, which were released in 2007 with version 3.5 of the .NET platform. The feature was added to support anonymous types and the relaxed programming style required by Linq.

Local type inference lets you define and use local variables without specifying their type. These variables are commonly called implicitly typed local variables because the compiler infers a strong data type from the initialization expression.

In Visual Basic, the compiler uses type inference to determine the data type without the "As" clause.

' Using explicit typing
Dim x as Integer = 3
 
' Using local type inference
Dim x = 3
 

In C#, you use the var keyword as shown in the following example:

// Using explicit typing
int x = 3;
 
// Using local type inference
var x = 3;
 

Here are some things to keep in mind when working with local type inference: