June 18th, 2013 | Ken Payson
Var is Better
In .NET 3.0 Microsoft introduced the var keyword. The primary reason for introducing the var keyword was to support anonymous types, but there are numerous benefits to using the var key word. I find that developers often still default to declaring variable types on the both the left and right side. Most of us have been writing code long before C# 3.0 and old habits are hard to break. But, there are reasons beyond habit that developers do not use the var keyword. Developers want their code to be readable and sometimes they believe that having the variable type visible on the start of the line helps the reader understand how the code works. I say that this shouldn’t be the case. There are situations that you cannot use the var key word. You cannot use it if you need to declare an out parameter. You cannot use it if you need the variable to be of an interface or a base class. You cannot use it for class variables. Other than these situations –
I say that using the var keyword is just better:
• Declaring variables with the type on the left hand side ex Widget myWidget = new Wiget() is repetitive. The compiler knows what the type of the variable is from the right hand side. (if you use the wrong type on the left you get a compilation error).
• With intellisense, you can always hover over the variable to see the type.
• It’s necessary to use var if you want to return an anonymous type.
• The var keyword makes your code look really neat with all your variable names lining up.
• The variable name, and the name of the function returning the value should tell you what you need know about the variable. You can use the extra space that you get by eliminating the type to give a more descriptive variable name.
• Using var makes it easier to refactor and maintain the code. Fewer things break when using var. If the right hand side changes. You don’t have to have to fix the left hand side also.
• You cannot say var foo = null because null is not a type. Using var makes it impossible to do the unnecessary initialization of variables to null. Now you have to set variables only when you have the correct value for them which is what you should do.