-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Description
Allow var variables to be used in a nameof in their initializers
- Proposed
- Prototype: Not Started
- Implementation: Not Started
- Specification: Not Started
Summary
Today, the following code is invalid:
var a = nameof(a);Despite this code being valid:
string a = nameof(a);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 a var variable this way.
Detailed design
We modify this section of the specification (edit is to the last bullet, in bold):
In the context of a local variable declaration, the identifier var acts as a contextual keyword (Keywords).When the local_variable_type is specified as var and no type named var is in scope, the declaration is an implicitly typed local variable declaration, whose type is inferred from the type of the associated initializer expression. Implicitly typed local variable declarations are subject to the following restrictions:
In the context of a local variable declaration, the identifier var acts as a contextual keyword (Keywords).When the local_variable_type is specified as
varand no type namedvaris in scope, the declaration is an implicitly typed local variable declaration, whose type is inferred from the type of the associated initializer expression. Implicitly typed local variable declarations are subject to the following restrictions:
- The local_variable_declaration cannot include multiple local_variable_declarators.
- The local_variable_declarator must include a local_variable_initializer.
- The local_variable_initializer must be an expression.
- The initializer expression must have a compile-time type.
- The initializer expression cannot refer to the declared variable itself except as the argument to a nameof_expression.
Drawbacks
All change is scary.
Alternatives
Do nothing.