Search code examples
c#.netsyntaxlanguage-specifications

type inference not working in several declaration cases


why the following statement is perfectly valid one

string a = "someString", b = a, c = a;

but this one does not compile

var a = "someString", b = a, c = a;

another example is here first, an error:

enter image description here

second OK:
enter image description here

I've seen a similar question here, but the context here is a little bit different:

If

var i = 2, j = 3.4;

is harder for the compiler to 'digest' (even there I don't see a problem to recognize one as int and the other as double), however

var a = "someString", b = a;

should be even less ambiguous, because:

var a = "someString", // here 'a' is inferred to 'string'

so the following

b = a; 

should be also inferred to string, because a has its type already defined...


Solution

  • TLDR: It is a design decision of the C# compiler team to eliminate this feature.

    As you can see, IntelliSense has already provided you with an error:

    CS0819: Implicitly-typed variables cannot have multiple declarators.

    The message, indicates that IntelliSense (and of course the C# compiler from which IntelliSense gets all its intelligence from) is perfectly aware of the situation and does not allow it.

    Why am I saying that it is perfectly aware of the situation?

    Using var to declare a variable is what we refer to as "declaring the type of a variable implicitly". "Having multiple declarators" is to make declarations like TypeName a = i, b = j. As a result, var a = "someString", b = a; (and the similar snips that you shared) can be accurately described as "using multiple declarators with implicit typing".

    So C# is explicitly saying: "I know what you're trying to do but you can't". But why?

    The reason is not one of an inherent limitation of the type system. It's actually not technical reason at all. The reason is due to a design decision that is described as an answer to the question that you mentioned by Eric Lippert: https://stackoverflow.com/a/4950600/10560397

    Eric tries to say that because there can be ambiguity when trying to infer what sits behind var in some cases, they decided to completely eliminate the ability to do multiple declarations with implicit typing.