It seems the C# ‘var’ is gaining more and more popular nowadays. More and more people like it and use it more often. It is true that using ‘var’ can save some typing and at the same time make code look concise.
However, is it good to use it always as some exercise in their coding and advocate to others?
It does not sound so.
One support for using 'var' is that the Visual Studio IDE can hint us what the ‘var’ really represents if the mouse cursor is hovering over it and people can generally guess out from the real expression by looking at the code itself even if editors not supporting intellisense are being used.
It is partially true. Using the following code for example, the return value of the method GetCustomers() most likely be some collections.
void UseVarAlways()
{
var all = GetCustomers();
var other = GetCustomers();
all.AddRange(other);
}
Ah, yes. The guess is correct in this case. The method is defined like this:
List<string> GetCustomers()
{
var customers = new List<string> { "A", "B", "C" };
return customers;
}
However, collection in .NET has various forms such as IEnumerable, IList and Dictionary and its element can be of all possible type such as some other collection and the Object. In addition, it is common and good for the same method to return an array too.
string[] GetCustomers()
{
var customers = new string[] { "A", "B", "C" };
return customers;
}
If this is the case, the code does not compile either, the same as some explicit return type being used. The following error will be complained by the compiler.
'System.Array' does not contain a definition for 'AddRange' and no extension method 'AddRange' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?)
The same fact also revokes the argument that using ‘var’ can get rid of issues caused by changes to method return types. It is only true if the return type and value is not used at all or only some very common property or method such as ‘Type’, ‘Name’, and ‘ToString()’ being used, but in reality it rarely happens. In the first situation, otherwise, the ‘var’ can also be saved. C# allows to call methods that way.
It is fortunate here that the compiler helps easily figure the problem. In some subtle cases however, tricky issues could happen if ‘var’ is always used and some method return types being changed. The reason is simple like this, the inferred type is not always as expected.
So, sugar could be good for health if used a little at right times, but could be very harmful if being abused.