Using var And Living With The Consequences

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();

into this:

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.

You see, I don’t entirely agree with using var.  Using var is fine, but we aren’t converting C# into a dynamically typed language like Python or JavaScript – C# is still statically typed, using var just forces the compiler to figure out the type you’re using, usually based on the first value assigned to it.  In Python or JavaScript I could take sb from the above example and assign to it the UTF8Encoding() object reference on the next line, but C# won’t let you do that, the compiler will give you an error.

I don’t like the illusion, so where possible I will use var, but I’ll keep using types too when necessary for clarity.

Leave a Reply

Your email address will not be published. Required fields are marked *