Implicitly Typed or Named Types

An Implicitly Typed Local Variable, var, is “new” and it is subject to restrictions:

    • The declarator must include an initializer.
    • The initializer must be an expression.
    • The initializer expression must have a compile-time type which cannot be the null type.
    • The local variable declaration cannot include multiple declarators.
    • The initializer cannot refer to the declared variable itself

Beyond the obvious use of var with LINQ, you may also clear the code for readability:

var d = new Dictionary<string, Dictionary<string, List<SomeClass>>>();

The entire debate around using the var is founded on readability.

Another pair of eyes see differently so the code has to self explain. That being said, using the var for just about anything is also an exageration. A method that returns a “hairy” type (like List<string>) would be easier to digest in a var but that would not tell those other pair of eyes anything about the purpose and the intention behind. So you would not know how that specific return was “intended to be used”. Just compare List<string> list = MyMethod():

  • var list = MyMethod()
  • IEnumerable<string> list MyMethod()

The second one is actually saying “I am not going to change this, use an index to access list members or modify members.”. It’s quite a lot to say in that few words. But it’s not over because it is also saying “I am going to use this list simply to iterate across it”.

The intention is what you are giving up if you use var. You are not giving anything up where the usage is obvious through the declaration.

var i = 5;
var s = “Hello”;
var d = 1.0;
var numbers = new int[] {1, 2, 3};
var orders = new Dictionary<int,Order>();

are equal to

int i = 5;
string s = “Hello”;
double d = 1.0;
int[] numbers = new int[] {1, 2, 3};
Dictionary<int,Order> orders = new Dictionary<int,Order>();

I’ would write a LINQ query like:

var rows = from DataRow r in parentRow.GetChildRows(myRelation)
where r.Field<bool>(“Flag”)
orderby r.Field<int>(“SortKey”)
select r;

But the debate is in the use of var, not in Anonymous Types, Object and Collection Initializers and Query Expressions, but everywhere in your code, for readability.

Here is Eric Lippert’s take on it:

All code is an abstraction. Is what the code is “really” doing is manipulating data? No. Numbers? Bits? No. Voltages? No. Electrons? Yes, but understanding the code at the level of electrons is a bad idea! The art of coding is figuring out what the right level of abstraction is for the audience.

In a high level language there is always this tension between WHAT the code does (semantically) and HOW the code accomplishes it. Maintenance programmers need to understand both the what and the how if they’re going to be successful in making changes. read more ..