When C# 3.0/.Net 3.5 was released one of the new features that was included was the 'var' keyword. Now I have to admit that when I first read about this new feature I immediately associated this 'var' with the Variant of VB6 or the var of JScript. But that could not be future from the truth.
The 'var' keyword was created to allow for anonymous types, these are types that at design time (code time if you will) do not have a concrete type, but at run time they do (compiler creates the concrete type for you). The var keyword is statically typed, it is not a new version of the Variant. Take a look at the code below:
var someVariableName = "Foo"; // this is typed as a string
var someVariableName = new SomeObject();
someVaraiableName = "Foo"; // this is NOT allowed
Enough of the history lesson, on to the point.
The use of the var keyword has had some controversy since it was announced, but as of late this 'var' war has heated up with some recent blog posts. Most notably there have been 2 posts that kinda sum up the general over all feeling on var. One for the general use and one against the general use of it.
In Jeff Atwood's (aka Coding Horror) post he talks about using var to remove redundancy. However, in Richard Dingwall's posts he thinks that Jeff has it all wrong. Well, I am here to tell the world that they are both wrong, yet both right (wow, what a way to pick a side Derik)...
No really, to be honest I was NOT in favor of the var keyword at first, but after giving it some thought and use, I LOVE the var keyword.
In Jeff's post he likes the var because he thinks it removed redundancy from your code (I 100% agree with this). However, Richard counters that saying that the use of var reduces readability. Well, again they are both right, but Jeff is soo much more right than Richard.
So, if I think they are both right, then how do I code an use the var? here are my rules for when the var should be used versus not used.
- Var should be used in all cases where the type can be visually inferred from the right side of the statement:
// Use var
var foo = "string";
var anotherFoo = new Object();
Both above we know the static type by looking at the code
- Var should NOT be used when rule 1 is not true:
// DO NOT USE var
var person = someObject.GetPerson();
Above I can assume that the GetPerson returns me a person object, but I am not 100% sure. In this case I would rather see something like below.
Person person = someObject.GetPerson();
Ok, now that I have cleaned up the 'var' war and everyone is happy again, it is time to tackle a larger problem like how to get my wife to allow me to have an iPhone. Wish me luck.
Till next time,
[----- Remember to check out DimeCasts.Net -----]
06-25-2008 5:30 AM