-
Notifications
You must be signed in to change notification settings - Fork 1k
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
[Proposal]: Allow var
variables to be used in a nameof
in their initializers
#4384
Comments
void Foo(int value, string paramName = nameof(value))
{
} isn't valid either, can this be covered as well? Thought the error is different but I'm curious to know why it isn't valid |
[return: NotNullIfNotNull(nameof(parameter))]
public static string? Foo(string? parameter)
{
} and this is not valid |
This is already tracked by another issue. |
No. please open a discussion on this :) Thanks! |
The following would then not be allowed, because it refers to var s = nameof(s.Length); |
Correct. That would involve knowing the type of
Let me dig into why that isn't allowed today. I'd be ok with supporting it. |
So, this comes down the scoping rules laid out here: https://github.com/dotnet/csharplang/blob/master/spec/basic-concepts.md#scopes. Specifically, the lines that read like:
This would be covered by #373, I think. |
So true. |
Should the following be allowed? I'd say no, but wanted to point out this scenario to consider. public class C
{
private string a = "";
public void M()
{
var a = nameof(a);
}
private static string nameof(object o) => "NameOfStaticMethod";
} |
Nope. A method call is not a nameof_expression. It is a good test case though. |
in regards to this sample: var s = nameof(s.Length);
the type can be inferred though. |
This particular use case is degenerate. But it could be more like |
Another thing is that the following code is also valid: dynamic s = nameof(s); |
Allow
var
variables to be used in anameof
in their initializersSummary
Today, the following code is invalid:
Despite this code being valid:
This proposal makes the first example legal.
Motivation
This is confusing to encounter (not helped by the bad Roslyn diagnostic we give, see dotnet/roslyn#45146, but that's beside the point), and takes some serious spec-lenses to understand why the restriction exists.
nameof(identifier)
is always a string, and we should make it fine to use avar
variable this way.Detailed design
We modify this section of the specification (edit is to the last bullet, in bold):
Drawbacks
All change is scary.
Alternatives
Do nothing.
Unresolved questions
Design meetings
https://github.com/dotnet/csharplang/blob/1754aaafffe270c19d8578af30a2eb768de3ee49/meetings/2021/LDM-2021-02-10.md#allow-var-variables-to-be-used-in-a-nameof-in-their-initializers
The text was updated successfully, but these errors were encountered: