Why doesn't C# let you declare multiple variables using var?

aarona picture aarona · Feb 9, 2011 · Viewed 16.2k times · Source

Given the following:

// not a problem
int i = 2, j = 3;

so it surprises me that this:

// compiler error: Implicitly-typed local variables cannot have multiple declarators
var i = 2, j = 3;

doesn't compile. Maybe there is something I don't understand about this (which is why I'm asking this)?

But why wouldn't the compiler realize that I meant:

var i = 2;
var j = 3;

which WOULD compile.

Answer

Eric Lippert picture Eric Lippert · Feb 9, 2011

When we designed the feature I asked the community what

var x = 1, y = 1.2;

should mean. The question and answers are here:

http://blogs.msdn.com/b/ericlippert/archive/2006/06/26/what-are-the-semantics-of-multiple-implicitly-typed-declarations-part-one.aspx

http://blogs.msdn.com/b/ericlippert/archive/2006/06/27/what-are-the-semantics-of-multiple-implicitly-typed-declarations-part-two.aspx

Briefly, about half the respondants said that the obviously correct thing to do was to make x and y both double, and about half the respondants said that the obviously correct thing to do was to make x int and y double.

(The language committee specified that it should be "double", and I actually implemented the code that way long before we shipped. We used the same type inference algorithm as we do for implicitly typed arrays, where all the expressions must be convertible to a best element type.)

When half your customer base thinks that one thing is "obviously correct" and the other half believes that the opposite is "obviously correct" then you have a big design problem on your hands. The solution was to make the whole thing illegal and avoid the problem.