Search code examples
c#declarationimplicit-typingvariable-declaration

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


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.


Solution

  • It's just another point of possible confusion for the programmer and the compiler.

    For example this is fine:

    double i = 2, j = 3.4;
    

    but what does this mean?

    var i = 2, j = 3.4;
    

    With syntactic sugar this kind of thing is a headache no one needs--so I doubt your case would ever be supported. It involves too much of the compiler trying to be a little bit too clever.