Skip to content

[Proposal]: Allow var variables to be used in a nameof in their initializers #4384

@333fred

Description

@333fred

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 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:

  • 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.

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

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions