I think it's just too iffy. When the two variables are the same type it's an easy specific case, but in the more general case you'd have to consider what is "correct" in code like:
var x = new object(), y = "Hello!", z = 5;
Should those all be typed as object
, since that's the only type they all have in common? Or should x
be object
, y
be string
, and z
be int
?
On the one hand you might think the former, since variables declared in this way (all on one line) are usually presumed to all be the same type. On the other hand perhaps you'd think it's the latter, since the var
keyword is typically supposed to get the compiler to infer the most specific type for you.
Better to just prohibit this altogether than bother working out exactly how it should behave, given that it would not exactly be a "killer" feature anyway.
That's my opinion/guess, at least.
var
is useful the initializers are usually rather long, and thus multiple statements are easier to read anyways. – Weaponryvar
in place ofint
. It's the same number of letters!int
is even easier to type, in my opinion ;) – Percolatorauto
is the C++0x equivalent of C#'svar
): it allows you to declare multiple variables in a singleauto
declaration, but the initializers must all be of the same type. So,auto i = 1, j = 2;
is ok because both initializers are of typeint
so theauto
meansint
here, butauto i = 1, j = 1.2;
is ill-formed because there is an ambiguity as to what theauto
should mean. The rules are essentially identical to the template argument deduction rules. [Maybe no one here cares about C++, but it's interesting to make the comparison.] – Praetorian