Here are a few reasons why I use var and why I think it rocks.
You may still disagree after reading this but below are my opinions which I’ve marked the blog post in the category “Flame Wars”.
I had a hard time expressing why I like VAR so much so I did some research to try and help me express my thoughts and ideas. My references are below.
Let’s take a look at some code.
Explicit
// Have to use the full namespace because System.ServiceModel.Channels.Binding conflicts
// with System.Windows.Forms.Binding. See “It doesn't require using directive” below.
System.ServiceModel.Channels.Binding binding = Bindings.GetBinding(address, false, false);
EndpointAddress endpoint = new EndpointAddress(new Uri(address));
using (ServiceStatusClient client = new ServiceStatusClient(binding, endpoint))
{
client.Open();
statusUpdates[address] = client.GetStatus();
Console.WriteLine("ServiceHealth: {0}", statusUpdates[address].Health);
client.Close();
}
VAR
var binding = Bindings.GetBinding(address, false, false);
var endpoint = new EndpointAddress(new Uri(address));
using (var client = new ServiceStatusClient(binding, endpoint))
{
client.Open();
statusUpdates[address] = client.GetStatus();
Console.WriteLine("ServiceHealth: {0}", statusUpdates[address].Health);
client.Close();
}
Readability
My first observation with these two versions of code is the fact that the explicit version isn’t any easier to read than the VAR version. I would argue that the explicit version is harder to read because my mind has to process more unnecessary data when trying to parse the code snippet. My goal is to ensure the code I’m reading is performing it task as expected.
EndpointAddress endpoint = new EndpointAddress(new Uri(address));
I read the previous line of code like this. I have a type EndPointAddress variable named “endpoint” with a value of a new EndPointAddress using the new URI of the provided address. Rather than I have a variable named “endpoint” with a value of a new EndPointAddress using the new URI of the provided address. Minor difference but a major one.
Basically I don’t need to identify the type in my head until I assign it. Once assigned then I know what the datatype in and can move on. Minor performance gain in not having to process the data until I need to.
See ReSharper’s point below about “removing code noise”.
Logic First
I would also like to state that using var allows you to get to the logic where most problems exist. As programmers all we do is manipulate memory. All we have to do is be sure we are doing it properly at the right times. I want to be able to see what the code is doing and if it’s doing what it should be. How many of your code defects are because of type issues? How many of your code defects are logic problems? Exactly. Here are some other people opinions.
Eglasius, a commenter on a StackOverflow states:
I will add a controversial view on it. Unless I am reading code from a book, I don't usually care what's the specific type for understanding some lines of code I am reading. Consider the .GetTableRectangle(e.Index), for which you are not showing the code that operates on it:
var itemRect = tabCaseNotes.GetTableRectangle(e.Index);
// do some operations on itemRect
While reading that specific code I will get more to understand it from the operations on itemRect than from its type. It can be IRectangle, Rectangle, CustomRectangle, and still won't say much on what the code is doing with it. Instead I care more for the itemRect.Height, itemRect.Width or itemRect.GetArea() along with the logic involved.
Dustyburwell, another commenter on StackOverflow also makes a good point:
This question is a really good way to start a flame war. However, you should do whatever you and whoever you're working with think is most readable. There are good arguments for both sides of the debate about var.
Matt Hamilton, another commenter on StackOverflow say it this way:
var orders = cust.Orders;
I don't care if Customer.Orders is IEnumerable, ObservableCollection or BindingList - all I want is to keep that list in memory to iterate over it or get its count or something later on.
Contrast the above declaration with:
ObservableCollection orders = cust.Orders;
To me, the type name is just noise. And if I go back and decide to change the type of the Customer.Orders down the track (say from ObservableCollection to IList) then I need to change that declaration too - something I wouldn't have to do if I'd used var in the first place.
Less Typing
Why should I have to explicitly declare my variables? The compiler can do this for me and I can again focus on logic. The same reason we have IntelliSense and other features in our development environments. To help us become more productive and write more code. Not that I agree with this but Scott Hanselman states we only have so many keystrokes so don’t waste them on typing Explicit datatypes.
JetBrains ReSharper Team Blog
Here is what the ReSharper team had to say. I agree with everything and it really helps me state how I feel because I just couldn’t express it myself.
With the ReSharper 4 nightly builds available, some people are complaining about numerious suggestions to convert explicit type to "var" keyword. Of course, you can hide this suggestion by using Options / Code Inspection / Inspection Severity, or by using Alt-Enter and selecting "Change severity" option. But what's the deal with implicitly typed locals, anyway? Using var keyword can significantly improve your code, not just save you some typing. However, it may require discipline to apply good practices when using implicitly typed variables. Here is my list:
Anonymous Types
This is pretty obvious - you cannot declare local variable of anonymous type without using var.
It induces better naming for local variables
When you read local variable declaration with explicit type, you have more information at that moment and something like "IUnitTestElement current" makes sense. However, when this local variable is used later, you read "current" which takes some time to figure out the meaning. Using "var currentElement" makes it easier to read at any place.
It induces better API
When you let compiler deduce type from method return type or property type, you have to have good types in the first place. When you don't have explicit type in the initialization expression, you have to have best names for members.
It induces variable initialization
It is generally a good practice to initialize variable in the declaration, and compiler needs initializer to infer type for local variable declared with "var" keyword.
It removes code noise
There are a lot of cases, when implicitly typed local will reduce amount of text developer needs to read, or rather skip. Declaring local variable from new object expression or cast expression requires specifying type twice, if we don't use "var". With generics it can lead to a lot of otherwise redundant code. Another example would be iteration variable in foreach over Dictionary.</TKEY,TVALUE>
It doesn't require using directive
With var, you don't have explicit reference to type, as compiler infers type for you, so you don't need to import namespace when you need a temporary variable.
References
http://resharper.blogspot.com/2008/03/varification-using-implicitly-typed.html
http://stackoverflow.com/questions/737835/resharper-and-var
http://stackoverflow.com/questions/1873873/why-does-resharper-want-to-use-var-for-everything
http://stackoverflow.com/questions/41479/use-of-var-keyword-in-c