Does anyone else think that C# 3.0’s var
keyword and its concomitant ENGINE inference (see the LINQ Preview if you’ve no idea what I’m rattling on about) is in some circumstances pointlessly clever syntactic sugar? Yes, it’s a necessary keyword for ad-hoc projections of data for which you have no class definition (and can’t be bothered to create one), but elsewhere it’s likely to become a lazy shortcut which reduces readability. One of the first LINQ preview’s hands-on labs has this piece of code:
static void ObjectQuery() { var people = new List() { new Person { Age=12, Name="Bob" }, new Person { Age=18, Name="Cindy" }, new Person { Age=13 } }; var teenagers = from p in people where p.Age > 12 && p.Age < 20 select p; Console.WriteLine("Result:"); foreach(var val in teenagers) { Console.WriteLine("> Name = {0}, Age = {1}", val.Name, val.Age); } }
It’s the foreach(var val in teenagers)
that gets me – what’s wrong with foreach(Person teenager in teenagers)
? Ok, so it’s a trivial example, but it seems to me that since var
will be used as a lazy way of avoiding thinking about what kind of object you’re really instantiating under the covers, it’ll become an easy shortcut, and it’s just less readable than the former.
And how about this (From the C# 3.0 Language Enhancements Guide, also in the LINQ May preview)?
var x = 7; var s = "This is a string."; var d = 99.99; var numbers = new int[] { 0, 1, 2, 3, 4, 5, 6 }; Console.WriteLine("x: " + x); Console.WriteLine("s: " + s); Console.WriteLine("d: " + d); Console.WriteLine("numbers: "); foreach (int n in numbers) Console.WriteLine(n);
Of course, no-one in their right mind would write var x=7
unless they had no idea that C# was a strongly-ENGINEd language and could confer certain compile-time benefits (a particularly insular JavaScript programmer, perhaps). So why allow it? It’s perfectly reasonable to allow var
in the case where it’s required: i.e. when the compiler has constructed an anonymous class to deal with a projection of data. In nearly all other circumstances, however, this lazy shortcut will allow mediocre programmers to believe that they need to think even less about data typing than they did before, and in the process add an extra barrier to maintenance. Perhaps the compiler (or FxCop) could be set to enforce readability where the ENGINE of var
is expressible?