Hello james,
When we were working on var support in ReSharper 4 the team quickly splitted
into two groups. One group, who had some background in functional languages
instantly adopted "var" and were using it whenever possible. They wanted
the way to var-ize all their code, they wanted analysis to var-ize on the
fly and so on. The other group, including myself, were quite skeptic about
var and we demanded more conservative analysis, like suggest var when type
is explicitly visible in initialization expression. We settled it down pretty
fast (with two independent analyses) and then moved onto extension methods.
What's interesting here, is that I since adopted using var almost everywhere.
Consider we have the code like this, in Unit Testing part of ReSharper (so
the context is known):
UnitTestElement current = GetFirstElement();
while (current != null)
{
... plenty of code where current is used several times ...
}
That's all good, when you see the declaration of current, but what if
declaration
is not immediately visible? It may be out of screen, hidden within 5 other
declarations and so on. You can't instantly tell what is "current". Current
element or may be current session or may be current position?
Using var here "emulates" the hidden declaration. It becomes obvious, that
name is somewhat wrong. It should be "currentElement". Note, that it is not
like Hungarian Notion, we don't encode type in the name. We give "hint" to
type in the name, and that's enough to understand type in any point within
a context (Unit Testing), not just variable declaration. Or like you may
have:
foreach(KeyValuePair<Element<string>, ValueHolder<int>> item in dict) {...}
Looks ugly. But when you change it to be var, you'd better rename iterator
variable to "pair", which has enough type information in the name. Compare:
foreach (var pair in dict) {...}
Also, var do not require importing namespace and usings sections are shorter.
Also var is well aligned with "if (" and though this is pure aesthetics,
I like it very much :)
Sincerely,
Ilya Ryzhenkov
JetBrains, Inc
http://www.jetbrains.com
"Develop with pleasure!"
j> By the way, you don't have to use var at all... if you know the
j> return type, you can (and should, IMO) use a strongly typed variable.
j> In fact, I'm not sure why ReSharper 4.0 keeps suggesting that we use
j> var where possible -- var may be easier to write, but I prefer to
j> keep things more explicit when I can.
j>
j> if you have
j>
j> var results = from s in personcollection
j> where s.Name=="my name"
j> select s;
j> you could also do this:
j>
j> IList<Person> results = (from s in personcollection
j> where s.Name=="my name"
j> select s).ToList();