For background see dotnet/roslyn#48754
The current compiler has some interesting behavior with regards to accessing instance members from a static context:
using System; public struct C { public string P; public static string M1() => nameof(P); // Legal public static string M2() => nameof(P.Length); // error CS0120: An object reference is required for the non-static field, method, or property 'C.P' }
Where even though P
is an instance member you can access it from a static context, but you can't access P.Length
.
The relevant part of the spec is this:
The meaning of the named_entity of a nameof_expression is the meaning of it as an expression; that is, either as a simple_name, a base_access or a member_access. However, where the lookup described in Simple names and Member access results in an error because an instance member was found in a static context, a nameof_expression produces no such error.
This is somewhat ambiguous, but can be interpreted as saying only the top level lookup ignores errors where an instance member was found in a static context, but nested lookups do not. See here dotnet/roslyn#48754 (comment).
My request here is twofold:
Update the spec from:
The meaning of the named_entity of a nameof_expression is the meaning of it as an expression; that is, either as a simple_name, a base_access or a member_access. However, where the lookup described in Simple names and Member access results in an error because an instance member was found in a static context, a nameof_expression produces no such error.
To
DrawbacksThe meaning of a named_entity is the meaning of it as an expression; that is, either as a simple_name, a base_access or a member_access. However, where the lookup described in Simple names and Member access results in an error because an instance member was found in a static context, a nameof_expression produces no such error.
This is not a particularly common scenario, and so probably not worth changing the spec for, if it's decided that the current implementation is not a bug.
Alternatives Unresolved questions Design meetingsalrz, yaakov-h, Unknown6656, PathogenDavid, nil4 and 25 more
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4