Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nameof can refer to a variable "early" #1111

Open
jskeet opened this issue May 16, 2024 · 3 comments
Open

nameof can refer to a variable "early" #1111

jskeet opened this issue May 16, 2024 · 3 comments
Labels
type: bug The Standard does not describe the language as intended or implemented

Comments

@jskeet
Copy link
Contributor

jskeet commented May 16, 2024

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 jskeet added the type: bug The Standard does not describe the language as intended or implemented label May 16, 2024
@KalleOlaviNiemitalo
Copy link
Contributor

The new wording shouldn't allow this, though:

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

@jskeet
Copy link
Contributor Author

jskeet commented May 16, 2024

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"

@KalleOlaviNiemitalo
Copy link
Contributor

KalleOlaviNiemitalo commented May 16, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: bug The Standard does not describe the language as intended or implemented
Projects
None yet
Development

No branches or pull requests

2 participants