Friday, May 22, 2009

Implicitly Type Local Variable & Multiple Declarators

It is perfectly legal in C# to have declarations written this

int x, y;
which with initialized values is
int x= 5, y=6;

Alas, the C# compiler rejects this
var x=5, y=6;

This is because the C# Compiler does not allow multiple declarators on the var keyword. I wondered where this is not allowed and if you ask me so much restrictions on the use of the var keyword (can't use as method return type or method arguments).

A recent mail from Eric Lippert clarifies this. His reasons for why this feature was made illegal was that of removal of confusion. In his own words

object M() {}
string N() {}
var x = M(), y = N();
about fifty percent of people thought that the “obvious” meaning was
object x = M();
string y = N();
That is, the “obvious” meaning is “split the two apart and do them separately”.
About fifty percent thought that the “obvious” meaning was
object x = M(), y = N();
That is, “find the thing that you could replace the ‘var’ with and pretend it was there”.
No matter which we picked, half our users would think that we did it wrong. So we cut that feature.  A “var” declaration can only have one variable declared

No comments: