# To var or not to var...

Interesting thread on the ALT.NET mailing list, where Ilya is talking about some of the debate on the ReSharper 4 team surrounding the new var keyword, and the rules they ended up using for R# suggestions.

In my .NET 3.5 work so far I have tended to shy away from var, preferring to be explicit about my type declarations. I even turned off R#’s suggestions to use var instead of an explicit type. After reading Ilya’s messages on the thread, I am reconsidering the issue, especially now I understand the logic behind when R# suggests var.

One of the conditions is when the right hand side of an initialisation explicitly shows the type. For example:

Dictionary<A,B> dict = new Dictionary<A,B>();
/* OR */
var dict = new Dictionary<A,B>();

In this case, why all the additional typing? We are already specifying what type we want, why duplicate it on the left and right sides of the expression? Both expressions are equivalent, we are just leaving the compiler to work out the obvious bits.

I’m beginning to think eliminating this duplication is a good thing. It removes a bit of noise from the code and let’s you focus on the important stuff, without losing any type safety.

Obviously care needs to be taken not to abuse this feature, but for simple cases where the type is immediately obvious from the code then I’m starting to think var might be the way to go.

Update 2008-03-05: Ilya has posted some more arguments in favour of using var on his blog.