12

I was just wondering how come nameof from C# 6, can access non static property just like if it was static. Here is an example

public class TestClass
{
    public string Name { get; set; }
}

public class Test
{
    public Test()
    {
        string name = nameof(TestClass.Name); // whats so speciall about nameof
        //string name2 = TestClass.Name; this won't compile obviously, 
    }
}
usr
  • 168,620
  • 35
  • 240
  • 369
adminSoftDK
  • 2,012
  • 1
  • 21
  • 41
  • 8
    There is nothing special about it. This happens at compile-time, not at runtime. And the compiler has no problem whatsoever to convert a member named Name into a string literal "Name". Only thing that's odd about it is why it took 6 versions to get added to the language :) – Hans Passant Sep 10 '16 at 14:42
  • you may found your answer here : http://stackoverflow.com/questions/31695900/what-is-the-purpose-of-nameof – Sunil Kumar Sep 10 '16 at 18:02

2 Answers2

16

It's not "accessing" the property - that operator is purely a compiler mechanism to inject the "name" of the argument into the code. In this case it will replace nameof(TestClass.Name) with "Name". The fact that it's non-static is irrelevant.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • 3
    Also, `nameof` can't access private members, your code does not work fine, it fails with: "CS0122 'A.Y' is inaccessible due to its protection level" – svick Sep 10 '16 at 16:25
7

nameof Interpreter gets resolved at compiletime and translated to a static string instead.
In your case nameof(TestClass.Name) you will only return "Name" as a string.
You have to use nameof(TestClass).
With nameof you can minimize redundancy in your code (For instance: you dont have to define a string for a propertyname or something like this by using nameof.

You can also use it to represent a classes name. But be aware! nameof(MyClass)
may not be the same as at runtime if you have an derived class! For runtime purposes use typeOf or .GetType() instead.

Read more at MSDN

Cadburry
  • 1,844
  • 10
  • 21