Mark Rae said:
I fully agree. Smacks too much of "Dim var As Variant" to me...
Even though C# makes a reasonable stab at choosing the most appropriate
datatype (
http://msdn.microsoft.com/en-us/library/bb384061.aspx), I prefer
to tell it what I mean explicitly rather than allow it to decide what it
thinks I mean implicitly...
C# doesn't just make a "reasonable stab" at choosing the type, it
deterimines clearly and definitively what the type to attach to the
identifier. The rule is very simple, the type choosen is the type of the
expression on the RHS of the assignment.
For the sake of balance consider this:-
MyClassWithALongName thing = new MyClassWithALongName();
compared to:-
var thing = new MyClassWithALongName();
There are places in code where we have 'Tramp' data, that is values held
that are 'just passing through'. In these cases var is helpful, e.g.;
A set of static methods in a library currently being developed:-
fnA() returns type X
fnB(X p) takes a parameter of type X
fnC(X p) also takes a parameter of type X
In tandem we have code that consumes the library currently looks like this:-
X a = Library.fnA();
Library.fnB(a);
Library.fnC(a);
Now the developer of the library decides that fnA should return Y and fnB,
fnC accept Y. The consumer code is now broken. However if the consumer
used var instead of X, it would no longer care whether X or Y is in use, its
not bothered by it and things continue to work as expected.
Generally I agree though just using var because you can is a bad idea, it
needs to be a considered choice where the circumstance warrants it. If it
weren't for anonymous types I don't think the language designers would have
added var.
If you think var is open to abuse just wait and see what happens when
developers get hold of dynamic in C# 4. That's equivalent to Dim x as
Object in VB6. Yikes!