Another new feature added in C# 3.5 to accommodate anonymous types is the introduction of the var type keyword. In his Coding Horror blog Jeff Atwood is extolling the virtues of using var to reduce type declaration redundancy. His example is converting:
StringBuilder sb = new StringBuilder(256); UTF8Encoding e = new UTF8Encoding(); MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
var sb = new StringBuilder(256); var e = new UTF8Encoding(); var md5 = new MD5CryptoServiceProvider();
His point is that declaring the type as StringBuilder and then assigning it a new StringBuilder is redundant – StringBuilder appears twice on that line of code, before and after the assignment operator (=). He makes an excellent point because the example using var is far more concise than the original example. Furthermore, we should be more interested in what is being assigned than what we’re assigning too (at least on that line of code). I find when I read the first block my eyes stick on the left-hand side of the assignment, but in the second example I read the right-hand side code instead.
As a side note. the excellent tool ReSharper 4.0 suggests using var for every local variable declaration by default. It’s one of the first things I changed in ReSharper when I started using it.
I don’t like the illusion, so where possible I will use var, but I’ll keep using types too when necessary for clarity.