dotnet / dotnet/csharpstandard

Work out how "nameof" interacts with "this"

Open
#931 4 comments 0 reactions 1 assignee Claimed by @jskeet View on GitHub
type: bug
Dominant language
C#
Stars
815
Forks
99
Avg merge
1d 14h
Merged PRs (30d)
16

Description

Originally reported on #926.

Some comments from @KalleOlaviNiemitalo

A surprising interaction with nameof:

```
struct S {
int i;

void M() {
string N() {
return nameof(this); // error CS1673
}

string O() {
return nameof(this.i); // error CS1673
}

string P() {
return nameof(i); // OK, returns "i"
}
}
}
```

To be checked:

- nameof(this) in a default parameter or in an attribute argument (thus not in the function body) in a local or anonymous function in a struct

```csharp
using System;
class DAttribute : Attribute {
public DAttribute(string s) {}
}
struct S {
int j;
void LeA() {
// OK
Action a = ([D(nameof(this.j))] int i) => {};
}
void LeD() {
// error CS1065, default value not allowed
Action action = (string s = nameof(this.j)) => {};
}
void LfA() {
// OK
void F([D(nameof(this.j))] int i) {}
}
void LfD() {
// error CS1673, cannot access this in local function
void F(string s = nameof(this.j)) {}
}
}
```

That seems pretty inconsistent. Why is `nameof(this.j)` allowed in an attribute argument in the parameter list, but not in a default parameter value? Is that what the standard should specify?

Expression trees seem to allow neither attributes nor default values, so the behaviour is more consistent for them:

```csharp
using System;
using System.Linq.Expressions;
class DAttribute : Attribute {
public DAttribute(string s) {}
}
struct S {
int j;
void ExA() {
// error CS8972, attribute not allowed in expression tree
Expression> e = ([D(nameof(this.j))] string s) => "";
}
void ExD() {
// error CS1065, default value not allowed in expression tree
Expression> e = (string s = nameof(this.j)) => "";
}
void ExR() {
// error CS1673, lambda expression in struct cannot access this
Expression> e = (string s) => nameof(this.j);
}
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.