dotnet / dotnet/roslyn

CS1673 is inappropriately reported for nameof(this.Xyz) in a lambda/local func in a struct instance member

Open
#78,983 0 comments 1 reaction 0 assignees View on GitHub
Area-Compilers
Dominant language
C#
Stars
20.7k
Forks
4.3k
PR merge metrics
PR metrics pending

Description

**Version Used**: 17.14.5 Preview 1.0

When using `nameof` with an instance member in a struct and qualifying the instance member access with `this.`, you are shown an error which is only relevant to accessing struct state, despite `nameof` not accessing state:

> Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.

The error is also inconsistent. It's not shown in local function/lambda attribute arguments, but it is in other usages inside local functions/lambdas, including default parameter values.

```cs
using System.ComponentModel;

struct S
{
void M()
{
void L(string p = nameof(this.M)) // error CS1673: ~"Stop accessing instance state"
{
_ = nameof(this.M); // error CS1673: ~"Stop accessing instance state"
}

void L2([DefaultValue(nameof(this.M))] string p) // No error!
{
}
}
}
```

### Workarounds

The workaround is to make an exception and drop the `this.` qualification when inside `nameof` inside a lambda or local function inside a struct instance member.

Contributor guide

Open the contributing guide

Research direction

Start by compiling the minimal C# struct example and compare the nameof usages that do and do not report CS1673. Trace the compiler's handling of nameof inside lambdas and local functions, then add coverage for the shown cases. Done means qualified nameof(this.M) no longer reports CS1673 in these contexts while genuine instance-state access remains diagnosed.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.