C# Var: The Religious War

I've been seeing a lot of people posting code examples that have the C# var keyword sprinkled liberally through their code. It's a handy little feature that helps you with LINQ queries, anonymous types, etc. For example, you can create a new type on the fly like this:


var person = new { Name = "Chris" };
Console.WriteLine(person.Name);
1
2

Not everyone reads from left to right, but I do, as does every single person who works with me and every single blog and code example I've ever seen. This is important when considering the liberal use of var because now one would have read a whole line of code and figure out the type for themselves, rather than just reading the first word on the line(if declaring a local variable).

Look at the following snippet:


var bus = FacilityConfig.Children["bus"];
if (bus == null)
  throw new InvalidOperationException("bus is a mandatory element");
1
2
3

What type is bus in the previous example? You would have to hope that you're in visual studio and can hover over it with the mouse pointer so you could see the type which is lame.

The var keyword should be used sparingly, only when the type is unknown, like in a linq query that returns an anonymous type. Using it in situations where you know what the type is makes your code hard to read.

 
Author: , 0000-00-00