How does the name work?

I'm just wondering how the nameof came out of C # 6, you can access a non-static property as if it were 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, } } 
+5
source share
2 answers

It does not "refer" to a property - this operator is a pure compiler mechanism for entering the "name" of an argument into code. In this case, it will replace nameof(TestClass.Name) with "Name" . The fact that it is non-static does not matter.

+9
source

nameof Interpreter will be resolved in compiletime and translated instead of static string .
In your case, nameof(TestClass.Name) you will return "Name" only as a string.
You should use nameof(TestClass) .
With nameof you can minimize redundancy in your code (for example: you don’t need to define a string for the property name or something like that with nameof .

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

More on MSDN

+4
source

All Articles