csharpstandard icon indicating copy to clipboard operation
csharpstandard copied to clipboard

nameof can refer to a variable "early"

Open jskeet opened this issue 1 year ago • 3 comments

Spotted in #608 by @KalleOlaviNiemitalo, but split off as it's not part of the change.

In statements.md:

The scope of a local constant is the block in which the declaration occurs. It is an error to refer to a local constant in a textual position that precedes the end of its constant_declarator.

But const string s = nameof(s); is fine, despite the reference in nameof(s) being before the end of the declarator.

It's possible that we just need a carve-out for nameof in this case.

jskeet avatar May 16 '24 06:05 jskeet

The new wording shouldn't allow this, though:

public class C {
    public void M() {
        const string a = nameof(b); // error CS0841
        const string b = "";
    }
}

KalleOlaviNiemitalo avatar May 16 '24 07:05 KalleOlaviNiemitalo

Indeed. Nor, I would suggest, this: const string a = nameof(b), b = nameof(a);

I suspect we should carve out an exception of just "nameof can take the name of the constant being declared within the declarator"

jskeet avatar May 16 '24 07:05 jskeet

Roslyn seems to allow this too

public class C {
    void M() {
        const string a = nameof(a.Length);
    }
}

even though the name being taken is not that of the local constant.

KalleOlaviNiemitalo avatar May 16 '24 08:05 KalleOlaviNiemitalo