Posted by: Cirilo Meggiolaro | 11/15/2008

Tip of the day #32 – var type

A variable declared as var type will have its type determined in compile time based on its initialization. When you work with anonymous types var is mandatory.

Some examples…

The following variables are similar. The compiler will determine the type to assign to var.

var i = 123;
int i = 123;

The following code contains an array of integers numbers and a collection of even numbers is created and the result assigned to a var object.

int[] myNumbers = { 7, 8, 10, 11, 15, 16, 19, 22, 35, 38, 41, 45, 52 };

var myEvenNumbers = from even in myNumbers
                                  where even % 2 == 0
                                  select even;

foreach (int evenNumber in myEvenNumbers)
{
     Console.WriteLine(evenNumber);
}

Var facts…

1. The var type is not a variant, and you can not assign different value types during its life cycle;

2. Only variables declared on the method scope can be implicitly declared as var;

3. Var cannot be initialized to null;

4. Var types are easy to work with and useful in some cases, especially with anonymous types but they may potentially make the code hard to read because the types are not obvious.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: