Stop Using var (C#)!

I just picked up Andrew Troelsen and Philip Japikse’s Pro C# 7 Eighth Edition to catch up on some of the more recent language and platform changes (being stuck in SharePoint 2010 for 8 years will do that to you!).

I remember picking up the second edition and reading that thing front-to-back in my early days when I was just starting out.  (At that time, I had already completed several .NET projects but I felt embarrassed after failing an interview and I was determined to make sure I understood the framework to it’s practical depths).  This is a book that I still highly recommend to all developers I work with; I’ve had just about every junior developer I’ve hired — and even some senior ones — to read key pieces of this book.

I’m already loving this revision.  Troelsen calls out one of my biggest peer pet peeves, the excessive usage of var :

…using var to declare local variables simply for the sake of doing so brings little to the table.  Doing so can be confusing to others reading your code because it becomes harder to quickly determine the underlying data type and, therefore, more difficult to understand the overall functionality of the variable.

In fact, it could be argued that the only time you would make use of the var keyword is when defining data returned from a LINQ query.  Remember, if you know you need and int, just declare an int!  Overuse of implicit typing (via the var keyword) is considered by most developers to be poor style in production code.

(Troelsen and Japiske 97-98)

This is one of the first settings in ReSharper I ask devs to switch to ensure that we always have explicit types because it just makes it easier to read.

My personal guidelines have been drawn from McConnell’s Code Complete where he writes:

The smaller part of the job of programming is writing a program so that the computer can read it; the larger part is writing it so that other humans can read it. Let [the reader] use their brain cells to understand the larger question of how your code works rather than the syntactic details of a specific expression. You write readable code because it helps other people to read your code.

(McConnell 733)

I encourage more of my peers to preach the gospel!

You may also like...

Leave a Reply

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

Just a little arithmetic... *