csharpstandard icon indicating copy to clipboard operation
csharpstandard copied to clipboard

declaration expression with var as type name

Open KalleOlaviNiemitalo opened this issue 11 months ago • 3 comments

Describe the bug

C# draft-v8 §12.17 (Declaration expressions) says:

A declaration expression that is a simple discard or where the local_variable_type is the identifier var is classified as an implicitly typed variable.

That should not apply if name lookup for var finds a type.

Example

using var = char;

class C {
    static void M(out char x) {
        x = 'U';
    }
    
    static void M(out int x) {
        x = 42;
    }
    
    static void N()
    {
        M(out var x);
    }
}

Expected behavior

In the call M(out var x), the declaration expression var x should not be classified as an implicitly typed variable. The call should unambiguously resolve to static void M(out char x).

(If var x were an implicitly typed variable as the current wording says, then the call would also match static void M(out int x) and the ambiguity would cause a compile-time error.)

Additional context

Found while looking for how the var contextual keyword is defined and whether the rules for notnull are similar (https://github.com/dotnet/csharpstandard/issues/1246#issuecomment-2603533085).

KalleOlaviNiemitalo avatar Jan 21 '25 09:01 KalleOlaviNiemitalo

A declaration expression that is a simple discard or where the local_variable_type is the identifier var is classified as an implicitly typed variable.

I had trouble even parsing that. A couple of options:

  1. Add commas:

A declaration expression that is a simple discard, or where the local_variable_type is the identifier var, is classified as an implicitly typed variable.

  1. Reorder it to put the result first:

A declaration expression is classified as an implicitly typed variable if it is a simple discard or if the local_variable_type is the identifier var.

(This isn't addressing the topic of the issue, but we might as well improve the clarity as well as correctness at the same time.)

It possible that we'll need bullet points here:

A declaration expression is classified as an implicitly typed variable if:

  • The declaration expression is a simple discard; or
  • The local_variable_type is the identifier var, and a name lookup for var does not find a type

(The end of the latter is just a sample.)

jskeet avatar Jan 21 '25 09:01 jskeet

https://github.com/dotnet/csharplang/issues/7918#issue-2121929241 proposed reserving the var and _ names, but that change is certainly not part of C# 8.

KalleOlaviNiemitalo avatar Jan 21 '25 10:01 KalleOlaviNiemitalo

Let's try to use "contextual keyword" in the description - ideally link to when it's a contextual keyword or not.

jskeet avatar Jan 22 '25 21:01 jskeet