nameof(ServiceResult<object>.Result)
, where ServiceResult<object>
is my custom type and Result
is the field of this type. ServiceResult<object>
is just a declaration of type, it doesn't have operator new and (), but official page of MS says nameof
accepts variable and its members. Why this expression works? I didn't see such declarations before.
Asked
Active
Viewed 110 times
1

Adventurer
- 73
- 1
- 4
-
2You will found your answer here https://stackoverflow.com/questions/29878137/nameof-with-generics – Marcus Höglund Mar 23 '18 at 07:53
-
2`nameof` returns the name of the symbol at compile time. In this case the symbol is `Result`. It doesn't *create* an instance of whatever the symbol's type is nor check its values. – Panagiotis Kanavos Mar 23 '18 at 08:14
1 Answers
5
The spec you mentioned is probably an old one, C# 6.0 nameof
operator reference:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/nameof
The argument to
nameof
must be a simple name, qualified name, member access, base access with a specified member, or this access with a specified member. The argument expression identifies a code definition, but it is never evaluated.
In your case, it's an expression. Similar to
nameof(C.Method2) -> "Method2"
from the examples list in that article.
Examples
using Stuff = Some.Cool.Functionality
class C {
static int Method1 (string x, int y) {}
static int Method1 (string x, string y) {}
int Method2 (int z) {}
string f<T>() => nameof(T);
}
var c = new C()
nameof(C) -> "C"
nameof(C.Method1) -> "Method1"
nameof(C.Method2) -> "Method2"
nameof(c.Method1) -> "Method1"
nameof(c.Method2) -> "Method2"
nameof(z) -> "z" // inside of Method2 ok, inside Method1 is a compiler error
nameof(Stuff) = "Stuff"
nameof(T) -> "T" // works inside of method but not in attributes on the method
nameof(f) -> "f"
nameof(f<T>) -> syntax error
nameof(f<>) -> syntax error
nameof(Method2()) -> error "This expression does not have a name"

Anton Sizikov
- 9,105
- 1
- 28
- 39