More than a year ago when I was reading about C# 3.0 and all the goodness attached to it I saw this new keyword called "var". At first, I thought it was something similar to what Variant means in VB6 or something like the Object type in .NET which is a catch all type bucket for any object in .NET (since everything is derieved from System.Object right?). Upon further review, I realized that my initial assumption was wrong and that var is whole different beast after all.
So what does "var" really do? Well for starters, var is strongly-typed while Variant and Object are not. Variants occupy alot of memory space when used and Objects have boxing and unboxing issues. "var" on the other hand doesn't have this problems. To further understand lets look at the example below:
Assuming that you want to declare a variable x of type int and assigning it with a value of 5:
int count = 5;
Looking at the snippet above you'll get the idea that the format for a variable declaration is as follows:
<type> <name> = <value|initializer>;
The important thing here is to realize that "count" is an integer. Now replace int with var:
var count = 5;
What happens here is that var automatically determines the datatype of the value you are assigning to it which in turn makes your var variable of that datatype.

So what is "var" exactly? Think of it as a shapeshifter. It takes whatever value you assign to it and it becomes that value and that type.
Posted
01-22-2008 4:20 PM
by
keithrull