C# 3.0 will be released in the near future and one of the new features that will be a part of our lives is Implicitly Typed Local Variables.

What that means is variables where the data type is automatically assumed.

The following example shows an explicitly typed variable:

int myValue = 4;

Specifying “int” informs the compiler that “myValue” will store an integer value.  This has always been the way in C#.  But C# 3.0 introduces a new keyword “var”.  This new keyword can be used to declare a variable without specifying a data type:

var myValue = 4;

Implicit data typing is nothing new (take JavaScript for example).  And infact the var keyword was used in this way in VB6.  However, the difference between VB6 and C# is that C# is a strongly typed language.

So if C# is strongly typed, how come we can get away without specifying a variable’s data type?  The reason is because the complier assumes the data type based on the variable’s initialization (that’s the bit where it says ‘= 4’).  In our previous example, we initialized the variable with the value 4.  4 is an integer and the compiler knows that.  Therefore myValue is assigned the datatype of int and it becomes type safe.  That is, it will only hold integers. 

Yes, this means there must be an initialisation when declaring the variable (and this must be an expression).  So the following is not permitted:

var myValue; // Invalid

This implicit data typing means that the variables are not the grossly inefficient ‘Variants’ seen in VB6.  They are the same variables in terms of memory usage as the equivalent datatypes in previous C# versions.

Now the question: Why?  Why introduce this confusion when it was already very simple to specify the data type?  I’m fairly certain the answer is to do with LINQ.

Without explaining LINQ in detail here, essentially it allows you to manage data in a relational database as objects – very nice.  Queries are integrated into the language itself (which are then translated into SQL).  

So imagine querying a database – What data / datatypes are going to be returned?  The answer is: it depends on the query of course.  So you could define a class for the results of each query, or a better way would be to use Implicitly Typed Local Variables:

foreach(var field in myQuery)
 Console.WriteLine(“{0}, {1}”, field.ID, field.Name);

Here we also see another application for Implicitly Typed Local Variables: We can use them in loops.

I hope this gave some introduction to the topic of Implicitly Typed Local Variables.  This is just one of the enhancements coming with C# 3.0