Implicitly Typed Local Variables in C# 3.0

Waqas Anwar
17 June 2009
21205 Views

Microsoft introduced quite a number of new features in C# 3.0 and later version and most of them are added in the language to support another new technology LINQ. One of those features is implicitly typed variables that allow you to create a local variable by using a newly added var keyword without giving it a specific type. In this tutorial I will give you introduction of implicitly typed variables and their use in your programs.

Implicitly typed local variable is a variable that can be declared without specifying the .NET type explicitly. The type of that variable will be inferred by the complier from the expression on the right side of initialization statement. Although implicitly typed local variables is not one of the exciting features of C# but they are introduced to support LINQ that create anonymous types in queries for which you want to assign variables. However, they are not only used with LINQ, you can declare and use them in your different programs.

To declare this type of variable you need to use new keyword var as follows:

var age = 50;
You can see although I am storing an integer value in the variable age but I am not giving variable a specific type such as int or System.Int32. When the compiler will see var keyword in code it will try to figure out the type of the variable automatically based on the value assigned to it. In the above case the type of variable age is System.Int32 and you can check it by calling GetType() method on the variable. This also means that you can call any System.Int32 function with the variable age as it has been given the System.Int32 type by the compiler.

So you can declare any type of implicit type variable in your code no matter they are normal objects, collections or even your own custom types. Here are two more easy examples of implicitly typed variable declarations.

var today = DateTime.Now;
var name = "Peter";

The following example is using var keyword not only to declare a variable of List collection type but also to iterate in a foreach loop.
var aList = new List();

aList.Add("HTML");
aList.Add("XML");
aList.Add("SQL");
aList.Add("PHP");

foreach (var item in aList)
{
   Console.WriteLine(item);
}

So far using these variables seems very straight forward but there are few important points to keep in mind when you are working with implicitly typed variables.

1. Implicitly typed local variables must be assigned a value at declaration time which means you have to give some value at declaration time. So the following code will not compile:

var age;      // will not compile
2. Implicitly typed local variable cannot have null as initial value that’s because compiler need to figure out what type of variable to declare by checking its value. So following will not compile:
var age = null;      // will not compile
3. Similar to the above rule an implicitly typed local variable cannot be Nullable variable which means the following syntax to create a Nullable variable in C# will not work with implicitly typed variables
int? age = null;      // will be fine

var? age = null;      // will not compile

4. Implicit Typed Variable cannot be used as class members such as field. They can only be used as local variables inside methods so following will also not compile:
class Person
{
   var name;      // will not compile
}

The above code will produce the following compile time error:

“The contextual keyword 'var' may only appear within a local variable declaration”


5. You can’t initialize it with an array for example the following code will not compile:
var items = { 1, 2, 3 };      // will not compile
You can use new implicitly typed array initializer syntax to create an implicitly typed array as follows:
var intArray = new[] {1, 2, 3};
var stringArray = new[] { "A", "B", "C" };

or even multidimensional array as follows:
var matrix = new[]
{
   new[] {1, 2, 3},
   new[] {4, 5, 6},
   new[] {7, 8, 9}
};

6. The implicitly-type local variable can’t be initialized with different types more than one time. You can’t assign the string to variable data after initializing it with integer value as following example shows:
var data = 10;
data = "Hello World";      // will not compile

To conclude this tutorial I will recommend you not to use implicit type variables if you already know the type of the variable you need in your program. Having said that, implicitly typed local variables are the best things to use when you are dealing with LINQ queries which return anonymous types and they help you to avoid creating a custom type for each LINQ result set.