Published

C# 3.0 – Implicitly Typed local variables

C# 3.0 introduces a new way to declare variables where the type applied can be inferred from the initializing expression. This is done using the keyword "var" instead of specifying explicitly the type. For example:

var text = "hello world" // type: string

var index = 12; // type: Int32

var people = new List(); // type: List

If you see the examples above you could think that the type used is a type variant or object, or any other type that encapsulates the real one. It is very important to understand that this is a wrong supposition. You can easily check that C# stills being a strong typed language, just adding the line "text = index;" to the examples above and tyring to compile. This will give you a compilation time error saying "Cannot implicitly convert type 'int' to 'string'", because text has been effectively declared as a string variable.

The easiest way to understand what it happens is considering the "var" keyword just as a token, which the compiler will replace by the real type and will produce exactly the same IL code as it we declare the variables using the traditional syntax. Let's take a look to the IL that the next C# code will produce:

As you can see the IL that declares and initialize text1 and text2 is exactly the same.

I've seen some other posts that talk about the benefits of this new syntax, since cleans the code and avoids us writing the type two times, which is redundant in declarations like "List people = new List();". This is true, but doesn't mean that we have a "go on" to use it in all our variable declarations. It has no sense to use it when we do something like "int index = 12;", because we don't avoid writing a single char and just makes the code a bit less readable.