In a book I'm reading it states the implicit typing makes the following code clearer than if you didn't use the var
keyword:
var words = new[] { "a", "b", null, "d" };
foreach (var item in words)
{
Console.WriteLine(item);
}
It seems to me that the opposite is true: if you used string
instead, then readers of the code would immediately know it was a string in the foreach loop, instead of having to look up in the code where the variable is defined.
How does implicit typing make the above code clearer?
Addendum
The book is C # 3.0 - Die Neuerungen. schnell + kompakt which is in German, the actual text is:
Das Schluesselwort var kann auch beim Durchlaufen von foreach-Schleifen verwendet werden, um somit den Code uebersichtlicher und einfacher zu gestalten. Besonders bei komplexen Typen kann man auf diese Art und Weise Programmierfehler verhindern.
here's my translation:
The var keyword can also be used when iterating through foreach loops, thus making the code easier and simpler to create. Especially when using complex types, this can prevent programming errors.
Ok, reading it more closely now he actually states that var
in a foreach loop makes the code easier to create but not necessarily easier to read.
It's clearer, in the sense of less noise/redundancy. The type of
words
can be easily deduced by thenew[] { ... }
statement, both by the compiler and the developer. Sovar
is used in stead ofstring[]
, as the latter can visually clutter the code.It's clearer, in the sense of transparency. You can swap the actual value with an instance of any other type, as long as it's an enumerable type. If you didn't use
var
, you'd have to change both of the declaration statements in the example.It's clearer, as it forces you to use good variable names. By using
var
, you cannot use the type declaration to indicate the contents of the variable, so you'll have to use a descriptive name. You only declare a variable once, but you may use it many times, so it's better to be able to figure out the contents of the variable by it's name. From this perspective,word
would have been a better choice for the loop variable name.Please note that the above reasoning is done from the author's perspective. It doesn't necessarily reflect my personal opinion :)
Edit regarding your addendum:
As I mentioned before, you can swap the underlying collection type, without having to update all your
foreach
loops. This does make it easier to create and change your code, but doesn't necessarily prevent programming errors. Let's look at both cases after we introduce aWord
class as a replacement of the plain strings:If we don't use the
var
keyword, the compiler will catch the error:If we do use
var
, the code will compile without errors, but the output of the program will be completely different, if theWord
class hasn't (properly) implementedToString()
.So, in certain cases subtle bugs can be introduced when you use
var
, which would have been caught by the compiler otherwise.It makes the code clearer when
Personally, I'd agree with you. I'm not sure if clearer is the word I would use but in certain situations the
var
keyword can certainly make it cleaner, i.e:If you wanted to make this code more explicit, I would suggest expanding the new instead of removing var:
Resharper will give you hints to remove redundant code with that example, but you can turn those hints off if you like.
The argument for using var is that in many cases the type identifiers for local variables are redundant, and redundant code should be removed. By removing redundant code, you can make the cases where you do actually care clearer, for example if you want to enforce a specific interface type for a local variable:
The primary benefit of explicit typing is in my view that it's possible by just looking at the code what type the variable has. So readability is increased.
And the primary benefits of implicit typing are:
It looks as if both options improve readability.
So I guess it depends on your preferences and maybe also on the programming guidelines in your team. With current (refactoring) tool support in IDE's it has become much easier to change type names (a no brainer) so the reason that implicit typing reduces changes has virtually disappeared from an effort perspective.
I'd suggest: Do what works best for you. There is no right or wrong. Try each approach for a while (e.g. by configuring the options of your favorite refactoring tool), then use what makes your life as a developer easier.
The example is poor, as many examples demonstrating syntactic sugar tend to be - syntactic sugar helps where things are complicated, but nobody likes complicated examples.
There are two cases where you might want to use
var
, and one where you must:Where you might want it:
IGrouping<int, IEnumerable<IGrouping<Uri, IGrouping<int, string>>>>
which can especially happen with intermeditary states within complex queries and enumeration operations.Personally, I prefer to use even the complicated form over
var
, as it doesn't cost someone reading it who doesn't care about the exact type (they can just skip it thinking "complicated grouping type"), but is clear to someone who does care without their having to work it out themselves.Where you need it:
In dealing with anonymous types, in code like:
Here res is an IEnumerable or IQueryable of an anonymous type, and i is of that anonymous type. Since the type has no name it's impossible to explicitly declare it.
In this last case, it is not syntactic sugar, but actually vital.
A related gripe, is that SharpDevelop used to have it's own while-editting form of var; one could type:
And at the semi-colon, the editor would produce:
Which gave (especially in more complicated cases) the advantage of typing speed along with producing explicit code. They seem to have dropped this now that var does conceptually the same thing, but it's a pity to have lost the typing shortcut to the explicit form.