adminSoftDK adminSoftDK - 2 months ago 7
C# Question

How does nameof work?

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,
}
}

Answer

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.