C#: Declaring implicit variables using var

This entry is part 8 of 71 in the series C#

Beginning in C# 3.0, variables can have an implicitly type var.

Consider the following 2 declarations which are functionally equivalent.

int i = 90 //explicitly declared as integer
var i = 90 //implicitly typed

An implicitly typed variable is strongly typed just as if you had declared the type yourself.  

The type will be determined by the compiler during compile time.

For example, we look at the following examples:

var firstNumber = 6;
var secondNumber = 3.5;
var thirdVariable = "This is a string!";

During compilation by Visual Studio, the compiler will determine that firstNumber is integer, secondNumber will be assigned as double and the thirdVariable will be assigned as a string.

Implicitly typed variables are strongly typed

When the compiler first see the following line

var a = 9

it will assign an integer to variable a.  If you later declare

a = 9.5 //9.5 is a double

The compiler will generate an error as it has already been determined to be an integer instead of a double.