Local Variable Type Inference

[Blog Map]  [Table of Contents]  [Next Topic]

Local variable type inference is a feature in C# 3.0 where you can use the var keyword instead of explicitly specifying the type of a variable.  The C# 3.0 compiler makes the type of the variable match the type of the right side of the assignment.  There are places when using C# 3.0 where we must do type inference when declaring variables; there is no other way, so we must cover this topic here.

This blog is inactive.
New blog: EricWhite.com/blog

Blog TOCLINQ query expressions (and many standard query operators) return a type of IEnumerable<T> for some type T.  When using LINQ, it is often convenient to make the type parameter be an anonymous type.  An anonymous type's name is automatically generated by the compiler, but hidden from the program.  If you write a query expression that creates an anonymous type, then the results of the query expression are an IEnumerable of the anonymous type.  To declare a variable to hold the results of such a query expression it is necessary to use type inference.  Anonymous types are introduced further on in this tutorial.

Simple Example of Type Inference

The following are a few local variable declarations with initializers:

int i = 5;
string s = "Hello";
double d = 1.0;
int[] numbers = new int[] { 1, 2, 3 };
Dictionary<int, string> orders = new Dictionary<int, string>();

The above code is precisely the same as:

var i = 5;
var s = "Hello";
var d = 1.0;
var numbers = new int[] { 1, 2, 3 };
var orders = new Dictionary<int, string>();

The var keyword tells the compiler to take the type on the right hand side, and use that type for the variable.  It specifically does not mean VARIANT, or Object.  The variables are strongly typed; the only difference is that the compiler is able to deduce the type from the initializer.

The topic on anonymous types shows examples where it is necessary to use type inference.

Limitations of Type Inference

Type inference can be used only for declaring variables with local scope. You can't declare the return value for a method using type inference, nor can you declare member variables of a class using it.

[Blog Map]  [Table of Contents]  [Next Topic]