How does implicit typing make code clearer?

2019-02-16 17:45发布

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.

13条回答
别忘想泡老子
2楼-- · 2019-02-16 18:29

In this case it doesn't, which is just my subjective opinion of course. I only use it when the type is elsewhere on the same line like:

var words = new List<String>();

I like var, but I wouldn't use it like in your example as it is not clear what the type is.

查看更多
登录 后发表回答